How to handle IPC between a service and an activity (and its subactivity)?

≡放荡痞女 提交于 2019-11-30 20:25:39

You want to have a single entity that is responsible for binding to the service and holding on to the connection and you need that entity NOT to be an Activity instance. Try this:

  • Create a base class (BaseActivity) that subclasses Activity
  • Derive all your activities from BaseActivity
  • Manage the connection between your application and your service using methods in BaseActivity. BaseActivity will need to have static (class) variables that keep track of the connection to the service and deal with binding to the service and shutting it down when you are done with it.
  • Make sure to use the application context (not the activity context) when binding to the service so that the OS won't kill the connection to the service when the activity is destroyed.

In this way you don't have to worry about creating and tearing down connections between the different activities and your service. There is only ever one connection between your entire application (all the activities) and your service.

I realize that I haven't explained all the gory details, but hopefully you get the basic idea.

Have you ever think about the following solution? Instead of bind Activity to Service, you can start your activity with the command startService() and then communicate with Intents and Receivers. In this way you can launch other activity, calling service for its state and interact with it wherever you want :)

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