Soheil
Soheil

Reputation: 1706

Start an Activity from a BroadcastReceiver

In my app, I register a BroadcastReceiver in the onCreate() method of a Service.

registerReceiver(receiver, newIntentFilter(myAction));

Now I need to start an activity from the newly registered BroadcastReceiver each time onReceive(Context context, Intent intent) happens:

Intent i = new Intent(context,MyClass.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);

The "context" is the Context which has been passed to my BroadcastReceiver. That successfully worked and started the Activity. Is that the correct and reliable way of starting an Activity inside a BraodcastReceiver from a Service? Because there are lots of was for getting the Context, like getApplicationContext() orgetApplication(), etc.

In my situation, is using the Context which has been passed to my BroadcastReceiver the correct way?

Upvotes: 5

Views: 7542

Answers (2)

Bardo91
Bardo91

Reputation: 585

It's possible to start the activity from the service using the "startActivity()" function.

Try something like this:

public void startAct() {
    Intent i = new Intent();
    i.setClass(this, MyActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);
}

and call the function inside your BroadcastReceiver.

android.app.Service is descendant of android.app.Context so you can use the startActivity method directly. However since you start this outside any activity you need to set FLAG_ACTIVITY_NEW_TASK flag on the intent.

Hope it helps.

Upvotes: 3

David Wasser
David Wasser

Reputation: 95578

The answer is "yes". You can use the Context that is passed as a parameter to onReceive() to start an activity. You can also use the application's context which you can get like this:

context.getApplicationContext().startActivity(i);

It makes no difference. Both will work.

Upvotes: 2

Related Questions