2015年4月29日 星期三

[Android] Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

今天看書練習Broadcast receiver時, 在自定義的BroadcastReceiver的類別onReceive()中, 我使用了一個intent想要將廣播收到的值抓出來再丟去瀏覽器查詢, 如下

    @Override
    public void onReceive(Context context, Intent intent) {
        String strQuery= intent.getStringExtra("QUERY_PARM");
        Uri uri = Uri.parse("https://www.google.com.tw/webhp?hl=zh-TW&gws_rd=ssl#hl=zh-TW&q=" + strQuery);

        Intent it = new Intent(Intent.ACTION_VIEW, uri);
        context.startActivity(it);
    }


但收到廣播後要開啟瀏覽器前, 程式就掛掉惹, 且DDMS出現了以下訊息:
 Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?


請問Google大神後, 發現如果是用context執行starActivity, 就需要再開一個新的task
解決方法就是在startActivity之前指派一個flag給intent 就OK了

        Intent it = new Intent(Intent.ACTION_VIEW, uri);
        it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(it);

沒有留言:

張貼留言