Question

One of the way to communicate between Activity and IntentService is to use BroadcastReceiver (or Local one) and "sendBroadcast()" method.

BroadcastReceiver is listening only when Activity is in onResume - onPause (visible lifecycle).

So what if:

  1. Activity is created and is visible so our BroadcastReceiver is listening
  2. we are starting new IntentService, this service is working in background... (for example connecting with server and checking something).
  3. Activity starts to be invisible because someone turn off screen. So in onPause method our BroadcastReceiver is unregistered.
  4. Intent service finish his task and make sendBroadcast to notify changed status or something else that activity should know. BUT now reciver is unregistered so this broadcast message dies.
  5. User turns screen on, activity is visible again (but it has no info from intent service). Intent service message IS LOST.

How to deal with this kind of situation? If we want Activity to have info about if intentservice stopped and end his job or something like that.

Was it helpful?

Solution

How to deal with this kind of situation?

You handle this the same way you handle all sorts of other situations, such as the user pressing BACK (thereby destroying the activity) and doing something in your UI to create a new instance of your activity.

Messaging from the service to the activity is a push interface, which is good for real-time updates. You also need a pull interface, where the activity can get the current status. And, in many cases, that also needs to take persistence into account, as the service, or even the entire process, may be long gone by the time a new activity instance needs to show those results.

Hence, the details will depend a lot on what the service is doing and how the UI can determine if that work is now completed and what the results are. That could involve querying a database, for example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top