Android 在 broadcast receiver 中调用 startActivity

在 broadcast receiver 中直接调用 startActivity,而不加入

FLAG_ACTIVITY_NEW_TASK

这个 flag 的话,将会报错,报错的形式类似如下这样:

java.lang.RuntimeException: Unable to start receiver 
XXXX.XXXXX.XXXXX.XXXBroadcastReceiver: 
android.util.AndroidRuntimeException:
Calling startActivity() from outside of an Activity  
context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
    at android.app.ActivityThread.handleReceiver(ActivityThread.java:2753)
    at android.app.ActivityThread.access$1800(ActivityThread.java:156)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1429)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5469)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Caused by: android.util.AndroidRuntimeException: Calling startActivity() from 
outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. 
Is this really what you want?
    at android.app.ContextImpl.startActivity(ContextImpl.java:675)
    at android.app.ContextImpl.startActivity(ContextImpl.java:662)
    at android.content.ContextWrapper.startActivity(ContextWrapper.java:331)
    at android.content.ContextWrapper.startActivity(ContextWrapper.java:331)
    at XXXX.XXXXX.XXXXX.XXXBroadcastReceiver.onReceive(XXXBroadcastReceiver.java:45)
    at android.app.ActivityThread.handleReceiver(ActivityThread.java:2741)
    at android.app.ActivityThread.access$1800(ActivityThread.java:156) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1429) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:5469) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

这段错误日志中,其实也已经提示我们可能需要使用 FLAG_ACTIVITY_NEW_TASK 参数了:

Caused by: android.util.AndroidRuntimeException: Calling startActivity() from 
outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. 
Is this really what you want?

那么我们就为我们创建的 Intent 对象加上 FLAG_ACTIVITY_NEW_TASK 属性,使其看起来像下面这样:

@Override
public void onReceive(Context context, Intent intent)   {

    Intent i = new Intent(context, AlarmDialog.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(i);    
}
    原文作者:赵者也
    原文地址: https://www.jianshu.com/p/9acfb8eda2ad
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞