Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 854
Soheil Avatar asked Oct 10 '13 21:10

Soheil


2 Answers

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.

like image 58
Bardo91 Avatar answered Oct 12 '22 11:10

Bardo91


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.

like image 44
David Wasser Avatar answered Oct 12 '22 10:10

David Wasser