1 /* 2 * Copyright (C) 2022 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.cts.tagging; 18 19 import android.app.Activity; 20 import android.app.Service; 21 import android.content.Intent; 22 import android.os.Handler; 23 import android.os.IBinder; 24 import android.os.Message; 25 import android.os.Messenger; 26 import android.os.RemoteException; 27 import android.util.Log; 28 29 public abstract class TestingService extends Service { 30 private static String TAG = TestingService.class.getName(); 31 32 // Message received from the client. 33 public static final int MSG_START_TEST = 1; 34 35 public static final int RESULT_TEST_UNKNOWN = Activity.RESULT_FIRST_USER + 1; 36 public static final int RESULT_TEST_SUCCESS = Activity.RESULT_FIRST_USER + 2; 37 public static final int RESULT_TEST_IGNORED = Activity.RESULT_FIRST_USER + 3; 38 public static final int RESULT_TEST_FAILED = Activity.RESULT_FIRST_USER + 4; 39 public static final int RESULT_TEST_CRASHED = Activity.RESULT_FIRST_USER + 5; 40 public static final int RESULT_TEST_BIND_FAILED = Activity.RESULT_FIRST_USER + 6; 41 42 // Messages sent to the client. 43 public static final int MSG_NOTIFY_TEST_RESULT = 2; 44 45 private Messenger mClient; 46 47 static class IncomingHandler extends Handler { 48 private TestingService mService; 49 IncomingHandler(TestingService service)50 IncomingHandler(TestingService service) { 51 mService = service; 52 } 53 54 @Override handleMessage(Message msg)55 public void handleMessage(Message msg) { 56 if (msg.what != MSG_START_TEST) { 57 Log.e(TAG, "TestingService received bad message: " + msg.what); 58 super.handleMessage(msg); 59 return; 60 } 61 mService.mClient = msg.replyTo; 62 mService.startTests(); 63 } 64 } 65 66 final Messenger mMessenger = new Messenger(new IncomingHandler(this)); 67 TestingService()68 public TestingService() { 69 } 70 71 @Override onBind(Intent intent)72 public IBinder onBind(Intent intent) { 73 return mMessenger.getBinder(); 74 } 75 notifyClientOfResult(int result)76 private void notifyClientOfResult(int result) { 77 try { 78 mClient.send(Message.obtain(null, MSG_NOTIFY_TEST_RESULT, result, 0, null)); 79 } catch (RemoteException e) { 80 Log.e(TAG, "Failed to send message back to client."); 81 } 82 } 83 startTests()84 private void startTests() { 85 int result = runTests(); 86 notifyClientOfResult(result); 87 } 88 runTests()89 protected abstract int runTests(); 90 } 91