FLAG_ACTIVITY_NEW_TASK使用場景及原理簡析

在非Activity(比如Service,BroadcastReceiver)中startActivity需要添加flag Intent.FLAG_ACTIVITY_NEW_TASK。否則會報Crash:android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag.

原文地址

以下Service爲前提說明

簡單來說:

每個Activity啓動都需要依賴一個Task棧,在Service中啓動Activity時一般使用ApplicationContext,它沒自己的Task棧,(Activity有自己的棧,但Service中保存Activity實例容易造成內存泄漏)。

補充說明:

在MainActivity啓動時,系統自動創建了App的Task棧,並且taskAffinity默認爲包名:com.test.haha
以下爲三種情況:

  • 情況1:只在Activity添加FLAG_ACTIVITY_NEW_TASK
    使用Task棧和MainActivity的Task棧是一樣的,因爲沒有在AndroidMainfest添加taskAffinity,那麼taskAffinity的默認值爲包名即com.test.haha

  • 情況2:只在AndroidMainfest添加taskAffinity 不添加flag,無效

  • 情況3:同時在Activity添加FLAG_ACTIVITY_NEW_TASK 和 在AndroidMainfest添加taskAffinity(若指定爲包名,則轉到情況1)

    則創建新的Task棧,行爲同啓動模式singleTask。

可以使用adb shell dumpsys activity activities 或者 打印getTaskId()來驗證。

請參考Google文檔:任務和返回棧

注意: 當調用者需要從啓動的Activity獲取返回結果時,不能使用此標誌。即使用startActivityForResult()要注意,沒有返回值的。(見官網註釋最後一句)

官網註釋:

FLAG_ACTIVITY_NEW_TASK

If set, this activity will become the start of a new task on this history stack. A task (from the activity that started it to the next task activity) defines an atomic group of activities that the user can move to. Tasks can be moved to the foreground and background; all of the activities inside of a particular task always remain in the same order. See Tasks and Back Stack for more information about tasks.

This flag is generally used by activities that want to present a “launcher” style behavior: they give the user a list of separate things that can be done, which otherwise run completely independently of the activity launching them.

When using this flag, if a task is already running for the activity you are now starting, then a new activity will not be started; instead, the current task will simply be brought to the front of the screen with the state it was last in. See FLAG_ACTIVITY_MULTIPLE_TASK for a flag to disable this behavior.

This flag can not be used when the caller is requesting a result from the activity being launched.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章