Is using Parcelable the right way to send data between applications?

前端 未结 3 847
野趣味
野趣味 2021-02-09 10:30

I am trying to understand how to communicate between applications in Android - not just between Activity instances.

I set up a \'client\' that sends a Messe

3条回答
  •  梦谈多话
    2021-02-09 11:12

    You cannot unmarshall a class at a process that has no knowledge of this class (as you already correctly pointed out). If you want MyParcelable to be sent to your Service, then you need to include MyParcelable in the Service at build, and include the right ClassLoader to be used when unmarshalling, because unmarshalling is done by a system thread, which doesn't know what MyParcelable is even if you included it at compile time.

    EDIT:

    (a) include MyParcelable into 2 different pkgs and have them be seen as the same class

    Make a library of your common classes and include it in both applications (the application and the Service). You can either mark it as an Android library (in Eclipse this is right under the project's Android properties) or export it as a JAR and import it in both apps. It's always a good idea to have independent classes in a library instead of putting them in the apps directly. This way you can reuse them on other projects ;)

    (2) include the right ClassLoader (where do I get the right class loader from, for example)

    You can get your ClassLoader from the current thread when you're executing your code. Obviously this ClassLoader knows about your classes because it's executing your code ;) For example in Activity#onCreate(), you can do Thread.currentThread.getContextClassLoader(). Since your MyParcelable class is also included on the Service, you can do the same to get a valid ClassLoader to unmarshall.

    Another solution for IPC is to define an AIDL interface so you don't have to implement Parcelable.

提交回复
热议问题