I'm trying to start an activity from a class that extends BroadcastReceiver.
public void onReceive(Context context, Intent intent) {
the problem is that parameter context is the Application context and not an Activity context.
Is there a way start an intent using the Application context?
In order to call startActivity with application context, include the flag FLAG_ACTIVITY_NEW_TASK. Also think about changing the name from context to appContext so it is clear which context you expect.
There is no way to pass the context to the target activity using Intent.
Application Context: It is the application and we are present in Application. For example - MyApplication(which extends Application class). It is an instance of MyApplication only. Activity Context: It is the activity and we are present in Activity.
Here is sample code how to call another activity using context, set flag as per your requirement:
public void onReceive(Context context, Intent intent) { Intent intent = new Intent(); intent.setClass(context, xxx.class); intent.setAction(xxx.class.getName()); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); context.startActivity(intent); }
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