Android bindservice绑定服务,并同步返回service对象的两个方法-CSDN博客
补充反射并调用bindServiceAsUser的方法:
private boolean initService2(final Context context){
if(deviceService==null){
latch = new CountDownLatch(1);
HandlerThread handlerthread = new HandlerThread("bindservice_thread");
handlerthread.start();
final Handler handler = new Handler(handlerthread.getLooper());
handler.post(new Runnable() {
@Override
public void run() {
try {
mConn=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder
iBinder) {
deviceService = IDeviceService.Stub.asInterface(iBinder);
isBind[0] =true;
latch.countDown();
}
@Override
public void onServiceDisconnected(ComponentName className) {
isBind[0] =false;
latch.countDown();
}
};
Intent intent = new Intent();
intent.setPackage("yourservicepackagename");
intent.setAction("yourserviceactionname");
Method bindServiceAsUser = Context.class.getDeclaredMethod("bindServiceAsUser"
, Intent.class, ServiceConnection.class,
int.class, Handler.class, UserHandle.class);
bindServiceAsUser.setAccessible(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
boolean bind= (boolean) bindServiceAsUser.invoke(context, intent, mConn, Context.BIND_AUTO_CREATE,
handler, UserHandle.getUserHandleForUid(android.os.Process.myUid()));
if(!bind){
isBind[0] =false;
latch.countDown();
}
}
} catch (NoSuchMethodException | IllegalAccessException |
InvocationTargetException e) {
e.printStackTrace();
isBind[0] =false;
latch.countDown();
}
}
});
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(!isBind[0])
return false;
}else{
return false;
}
return true;
}