How to start an Intent if context is not Activity Context but Application Context
26,936
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);
}
Author by
MataMix
Updated on December 17, 2021Comments
-
MataMix over 2 years
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?
-
tophyr almost 9 yearsThis is incorrect; Application contexts are not allowed to start Activities unless the Intent contains the FLAG_ACTIVITY_NEW_TASK flag.
-
Alon almost 8 yearsThis answer, while works, is vague in answering the question. 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.
-
Anand Khinvasara over 5 yearsOn Android pie FLAG_ACTIVITY_NEW_TASK does not help
-
androidguy over 5 years@AnandKhinvasara Do you have a citation do developer docs? Or is this an undocumented behavior?
-
MNassar over 4 yearsWhy do we need to provide the NEW_TASK flag? Because I tried starting an activity from an app context without this flag, and it worked fine.
-
Davide about 2 years