ClassCastException when binding to local service from another Activity

天大地大妈咪最大 提交于 2019-12-04 05:20:16

问题


In my application I have two separated APKs. The Activity (A1) from the first APK starts local service and is able to call methods provided by this Service. Later the activity A1 starts another activity (A2) from the second APK. The A2 activity tries to connect to the local service started by A1. Both activities are running in the same process with the same SharedUserID. Service interface is provided as shown in API examples of LocalService. onBind method of service returns LocalBinder instance which has method getService(). When onServiceConnected of A2 is called I got ClassCastException when I try to cast from IBinder to MyService.LocalBinder.

In the debugger I can see that the service argument of onServiceConnected of A2 activity is the right instance of MyService.LocalBinder. I can even watch all attributes of MyService in debugger, but when I tries to cast the IBinder service to the MyService.LocalBinder I got the ClassCastException exception? Is there some way around or do I have to use AIDL?

public void onServiceConnected(ComponentName className, IBinder service)
{

  try
  {
       MyService.LocalBinder binder = (MyService.LocalBinder)service;
       m_IService = binder.getService();
  }
  catch(ClassCastException e)
  {

  }


 }

回答1:


Not sure about this, but I'm guessing that you have compiled MyService.LocalBinder into both A1 and A2 apks. That would produce this kind of exception, because while they have the same name and the same code, they're still two separate class files. I think you would need to move the class into a shared library to make this work.


Update (responding to comment): I don't see how using an interface would be any different; as with the class, the interface would be instantiated differently on the client and server, and so result in a cast exception. You might be able to use reflection to work around this, but I don't recommend that approach -- it may not be supported by either AndroidOS or the DalvikVM.

I think the best course is to try creating the AIDL interface and see if it does the job. It could be 10x easier than trying to do something that Android seems deliberately designed to prevent.

But if you want to keep pursuing your current approach, one possible path would be to use the ClassLoader to load the client class into the server. I'm not sure if this can be made to work either.



来源:https://stackoverflow.com/questions/4526938/classcastexception-when-binding-to-local-service-from-another-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!