1 /*
2  * Copyright (C) 2016 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.externalservice.service;
18 
19 import android.app.Service;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.os.IBinder;
23 import android.os.Handler;
24 import android.os.Message;
25 import android.os.Messenger;
26 import android.os.Process;
27 import android.os.RemoteException;
28 import android.util.Log;
29 
30 import android.externalservice.common.ServiceMessages;
31 
32 public class BaseService extends Service {
33     private static final String TAG = "ExternalServiceTest.Service";
34 
35     private final Handler mHandler = new BaseHandler(this);
36     private final Messenger mMessenger = new Messenger(mHandler);
37 
38     @Override
onBind(Intent intent)39     public IBinder onBind(Intent intent) {
40         Log.d(TAG, "onBind " + intent);
41         return mMessenger.getBinder();
42     }
43 
44     static class BaseHandler extends Handler {
45         private Context mContext;
46 
BaseHandler(Context context)47         public BaseHandler(Context context) {
48             mContext = context;
49         }
50 
51         @Override
handleMessage(Message msg)52         public void handleMessage(Message msg) {
53             Log.d(TAG, "Received message: " + msg);
54             switch (msg.what) {
55                 case ServiceMessages.MSG_IDENTIFY:
56                     Message reply = Message.obtain(null, ServiceMessages.MSG_IDENTIFY_RESPONSE,
57                             Process.myUid(), Process.myPid());
58                     reply.getData().putString(ServiceMessages.IDENTIFY_PACKAGE,
59                             mContext.getPackageName());
60                     try {
61                         msg.replyTo.send(reply);
62                     } catch (RemoteException e) {
63                         Log.e(TAG, "Error sending MSG_IDENTIFY_RESPONSE", e);
64                     }
65                     break;
66             }
67             super.handleMessage(msg);
68         }
69     }
70 }
71