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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With