我正在尝试为反应本机应用程序构建和运行服务,并且在服务运行后我需要调用一些服务方法这意味着我需要获取正在运行的服务的实例所以我尝试使用 bindservice ()。
问题是,当我调用 bindservice() 时,onServiceConnected() 和 onStartCommand() 不会启动,另一方面,服务中的 onBind() 正在启动。
我试过的所有答案都没有帮助,这是其中的一部分:
ServiceConnection.onServiceConnected() 在绑定到已启动的 服务后从未调用 onServiceConnected 在 bindService 方法之后从未调用 ServiceConnection::onServiceConnected 即使 Context::bindService 返回 true 也未调用? OnServiceConnected 没有被调用
提前致谢。
这是服务:
public class TestService extends Service {
private LocalBinder mBinder = new LocalBinder();
private Intent serviceIntent;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.i("service", "service starting!!@!@!@ ");
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "ondestroy!");
Intent broadcastIntent = new Intent("com.testapp.service.RestartTest");
sendBroadcast(broadcastIntent);
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Intent broadcastIntent = new Intent("com.testapp.service.RestartTest");
sendBroadcast(broadcastIntent);
super.onTaskRemoved(rootIntent);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalBinder extends Binder {
TesService getService() {
return TestService.this;
}
}
}
react native 的包:
public class TestPackage implements ReactPackage {
private ReactApplicationContext applicationContext;
TestService runningService;
boolean mBound = false;
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
runningService = new TestService(reactContext);
Intent serviceIntent = new Intent(reactContext, runningService.getClass());
reactContext.bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
modules.add(runningService.someMoudle());
return modules;
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
runningService = ((LocalBinder) service).getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
AndroidManifest.xml
包含_
<service
android:name=".TestService">
</service>