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);  
}
Share:
26,936
MataMix
Author by

MataMix

Updated on December 17, 2021

Comments

  • MataMix
    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
    tophyr almost 9 years
    This is incorrect; Application contexts are not allowed to start Activities unless the Intent contains the FLAG_ACTIVITY_NEW_TASK flag.
  • Alon
    Alon almost 8 years
    This 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
    Anand Khinvasara over 5 years
    On Android pie FLAG_ACTIVITY_NEW_TASK does not help
  • androidguy
    androidguy over 5 years
    @AnandKhinvasara Do you have a citation do developer docs? Or is this an undocumented behavior?
  • MNassar
    MNassar over 4 years
    Why 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
    Davide about 2 years