39

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
MataMix
  • 3,276
  • 10
  • 39
  • 58

1 Answers1

56

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);  
}
Jemshit
  • 9,501
  • 5
  • 69
  • 106
SBJ
  • 4,089
  • 3
  • 24
  • 27
  • 34
    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. – Alon Jul 21 '16 at 17:06
  • 3
    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. – MNassar Jan 16 '20 at 09:54