android activity中 Task日常中使用

關於android:taskAffinity這個屬性在日常開發中不一定能用到,但是在某些特殊的場景下就會發揮很好的作用。

在介紹這個屬性前先要了解一些關於任務和返回棧的概念。
任務是指在執行特定作業時與用戶交互的一系列 Activity。 這些 Activity 按照各自的打開順序排列在堆棧(即“返回棧”)中。
根據android官網中的解釋:
(https://developer.android.com/guide/topics/manifest/activity-element.html#aff+%20+%22link%22)

android:taskAffinity

The task that the activity has an affinity for. Activities with the same affinity conceptually belong to the same task (to the same “application” from the user’s perspective). The affinity of a task is determined by the affinity of its root activity.
The affinity determines two things — the task that the activity is re-parented to (see the allowTaskReparenting attribute) and the task that will house the activity when it is launched with the FLAG_ACTIVITY_NEW_TASK flag.

By default, all activities in an application have the same affinity. You can set this attribute to group them differently, and even place activities defined in different applications within the same task. To specify that the activity does not have an affinity for any task, set it to an empty string.

If this attribute is not set, the activity inherits the affinity set for the application (see the element’s taskAffinity attribute). The name of the default affinity for an application is the package name set by the element.

前面囉嗦的解釋已經說過了。下面來介紹我在項目中的應用場景。

在開發的時候難免會遇到這種需求,需要對外提供接口以供其他應該調用,我在最近的項目中對外提供aidl,別的同事通過裏面的接口調用我的功能,在實現相關功能的同時還需要有界面展示。這就是大概功能。

我這通過對話框的形式來展現一些控制功能,對話框是依賴activity的,所以我以一個透明的activity作爲依託在調用我這功能的時候先啓動該透明的activity,然後在activity中啓動對話框,在對話框銷燬的時候finish()掉activity。但是這個恰恰買下了隱患。

當同事用另外一個應用調用我的接口時正常沒有問題。但是如果啓動了我的應用然後按home,再調用我的接口,在dialog結束後我的應用會被調起。

究其原因就是因爲這個透明的activity和我其他應用的activity使用的是同一個taskAffinity(Activities with the same affinity conceptually belong to the same task)這樣一來在dialog銷燬後銷燬透明activity這樣之前被home到後臺的界面就顯示了出來。

如果想更加直觀的看到這個現象可以adb shell dumpsys activity activities > c:a.txt將當前task還有stack打印出來,可以很直觀的看到這個現象。會發現透明activity和我的應用的主界面是同屬一個Task的,這樣根據
這裏寫圖片描述
可以看出出現該問題的原因在此。

解決方案很簡單就是對這個透明的activity使用自定的taskAffinity,自己寫一個就ok了。除了這種解決方案還可以通過singleInstance的launch mode來解決此問題。

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