在BroadcastReceiver中啟動Activity的問題
來源:程序員人生 發布時間:2014-12-23 08:08:18 閱讀次數:3027次
/**
* Demo描寫:
* 在BroadcastReceiver中啟動Activity的問題
*
* 如果在BroadcastReceiver的onReceive()方法中以下啟動1個Activity
* Intent intent=new Intent(context,AnotherActivity.class);
* context.startActivity(intent);
* 可捕獲異常信息:
* android.util.AndroidRuntimeException:
* Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag.
* Is this really what you want?
* 它說明:在Activity的context(上下文環境)以外調用startActivity()方法時
* 需要給Intent設置1個flag:FLAG_ACTIVITY_NEW_TASK
*
* 所以在BroadcastReceiver的onReceive()方法中啟動Activity應寫為:
* Intent intent=new Intent(context,AnotherActivity.class);
* intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
* context.startActivity(intent);
*
*
* 之前描寫了問題的現象和解決辦法,現在試著解釋1下緣由:
* 1 在普通情況下,必須要有前1個Activity的Context,才能啟動后1個Activity
* 2 但是在BroadcastReceiver里面是沒有Activity的Context的
* 3 對startActivity()方法,源碼中有這么1段描寫:
* Note that if this method is being called from outside of an
* {@link android.app.Activity} Context, then the Intent must include
* the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag. This is because,
* without being started from an existing Activity, there is no existing
* task in which to place the new activity and thus it needs to be placed
* in its own separate task.
* 說白了就是如果不加這個flag就沒有1個Task來寄存新啟動的Activity.
*
* 4 其實該flag和設置Activity的LaunchMode為SingleTask的效果是1樣的
*
*
* 如有更加深入的理解,請指導,多謝
*
*/
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈