ControlAltDelete
ControlAltDelete

Reputation: 3724

Pass context with intent

I have a broadcast receiver that will start an intent service to do some work on a separate thread.

I have tried digging into the Intent Documentation to find a way to obtain the context that is used to create the intent:

Intent(Context packageContext, Class<?> cls)

However the signature of on start command is the following and does not allow you to get to the context that is passed. I did not see a get context as a public method for intent, but I could have missed something.

public int onStartCommand(Intent intent, int flag, int startId)

Is there a way to get at the context that was used to create the intent without going the route of a second broadcast back the receiver to access the UI, or a handler.

Upvotes: 2

Views: 8885

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007634

I have tried digging into the Intent Documentation to find a way to obtain the context that is used to create the intent

Since that Context may not be in your process, that is not possible. Moreover, it is not necessary.

Is there a way to get at the context that was used to create the intent without going the route of a second broadcast back the receiver to access the UI

The BroadcastReceiver cannot update the UI. Hence, even if what you wanted was possible (which it is not), it would do you no good.

Moreover, since you are kicking off an IntentService, you may not have a UI. The user is in control of their phone, and so they are perfectly welcome to leave your app and go to the home screen or another app.

One pattern for dealing with this is to send an ordered broadcast from the IntentService. Have the activity implement a high-priority BroadcastReceiver for that broadcast, with a normal-priority receiver registered in the manifest. The latter would raise a Notification, so if your activity is not in the foreground, the user will see the Notification instead. Here is a blog post going into a bit more detail, and here is a sample application demonstrating this technique.

Upvotes: 1

Related Questions