Imported Upstream version 1.41.0
[platform/upstream/grpc.git] / src / core / ext / transport / binder / java / io / grpc / binder / cpp / SyncServiceConnection.java
1 // Copyright 2021 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package io.grpc.binder.cpp;
16
17 import android.content.ComponentName;
18 import android.content.Context;
19 import android.content.Intent;
20 import android.content.ServiceConnection;
21 import android.os.IBinder;
22 import android.util.Log;
23
24 /* Connects to a service synchronously */
25 public class SyncServiceConnection implements ServiceConnection {
26   private final String logTag = "SyncServiceConnection";
27
28   private Context mContext;
29   private IBinder mService;
30
31   public SyncServiceConnection(Context context) {
32     mContext = context;
33   }
34
35   @Override
36   public void onServiceConnected(ComponentName className, IBinder service) {
37     Log.e(logTag, "Service has connected: ");
38     synchronized (this) {
39       mService = service;
40     }
41   }
42
43   @Override
44   public void onServiceDisconnected(ComponentName className) {
45     Log.e(logTag, "Service has disconnected: ");
46   }
47
48   public void tryConnect(String pkg, String cls) {
49     synchronized (this) {
50       Intent intent = new Intent("grpc.io.action.BIND");
51       ComponentName compName = new ComponentName(pkg, cls);
52       intent.setComponent(compName);
53       // Will return true if the system is in the process of bringing up a service that your client
54       // has permission to bind to; false if the system couldn't find the service or if your client
55       // doesn't have permission to bind to it
56       boolean result = mContext.bindService(intent, this, Context.BIND_AUTO_CREATE);
57       if (result) {
58         Log.e(logTag, "bindService ok");
59       } else {
60         Log.e(logTag, "bindService not ok");
61       }
62     }
63   }
64
65   public IBinder getIBinder() {
66     return mService;
67   }
68 }