How to start an Intent if context is not Activity

2019-02-11 11:54发布

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?

2条回答
贪生不怕死
2楼-- · 2019-02-11 12:22

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 startActivity = new Intent();  
  startActivity.setClass(context, xxx.class); 
  startActivity.setAction(xxx.class.getName()); 
  startActivity.setFlags( 
              Intent.FLAG_ACTIVITY_NEW_TASK 
              | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 
  context.startActivity(startActivity); 
}
查看更多
forever°为你锁心
3楼-- · 2019-02-11 12:34

Yup, simply use the context and call the startActivity() method from that context.

查看更多
登录 后发表回答