在 broadcast receiver 中直接調(diào)用 startActivity,而不加入
FLAG_ACTIVITY_NEW_TASK
這個(gè) flag 的話锅很,將會(huì)報(bào)錯(cuò)缤灵,報(bào)錯(cuò)的形式類似如下這樣:
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)
這段錯(cuò)誤日志中,其實(shí)也已經(jīng)提示我們可能需要使用 FLAG_ACTIVITY_NEW_TASK 參數(shù)了:
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?
那么我們就為我們創(chuàng)建的 Intent 對(duì)象加上 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);
}