我们绑定到Application子类中的本地服务(相同的进程),但有时我们得到一个ClassCastException。我不知道如何修复它,因为每个人都说如果服务进程与您的应用程序不同,则会发生异常。如何解决这个问题?
应用程序子类:
public class App extends Application implements ServiceConnection {
private ServiceApi exposedServiceApi;
private EventBus eventBus;
@Override public void onCreate() {
super.onCreate();
bindToService();
}
public void bindToService() {
if (isConnectedToService()) {
return;
}
boolean successfulBindCall =
bindService(new Intent(this, MainService.class), this, BIND_IMPORTANT | BIND_AUTO_CREATE);
if (successfulBindCall) {
Timber.d("bindService() returned true --> onServiceConnected() will be called soon.");
} else {
throw new RuntimeException("bindService() returned false, this is an unrecoverable state.");
}
}
@Override public void onServiceConnected(ComponentName componentName, IBinder service) {
Timber.d("App has connected to service %s", componentName.toShortString());
if (componentName.getClassName().equals(MainService.class.getName())) {
try {
exposedServiceApi = (ServiceApi) service;
eventBus.post(new MainServiceConnectedEvent());
} catch (ClassCastException e) {
Timber.e(e, "Could not cast IBinder to ServiceApi!");
exposedServiceApi = null;
}
}
}
@Override public void onServiceDisconnected(ComponentName componentName) {
Timber.d("App has disconnected from service %s", componentName.toShortString());
if (componentName.getClassName().equals(MainService.class.getName())) {
exposedServiceApi = null;
eventBus.post(new MainServiceDisconnectedEvent());
}
}
}
Service.onBind():
@Override public IBinder onBind(Intent intent) {
return new ServiceBinder();
}
ServiceBinder :( MainService的内部类)
private class ServiceBinder extends Binder implements ServiceApi {
// implementation of ServiceApi
}
清单:
<service
android:name=".service.MainService"
android:exported="false"
android:icon="@drawable/ic_launcher"
android:stopWithTask="true"/>
错误:
java.lang.ClassCastException:android.os.BinderProxy无法强制转换为 ee.mtakso.driver.service.ServiceApi 在ee.mtakso.App.onServiceConnected(App.java:152) 在android.app.LoadedApk $ ServiceDispatcher.doConnected(LoadedApk.java:1139) 在android.app.LoadedApk $ ServiceDispatcher $ RunConnection.run(LoadedApk.java:1156) 在android.os.Handler.handleCallback(Handler.java:725) 在android.os.Handler.dispatchMessage(Handler.java:92) 在android.os.Looper.loop(Looper.java:153) 在android.app.ActivityThread.main(ActivityThread.java:5341) at java.lang.reflect.Method.invokeNative(Method.java) 在java.lang.reflect.Method.invoke(Method.java:511) 在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:929) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696) 在dalvik.system.NativeStart.main(NativeStart.java)