解決Android 按Home鍵時無法從後臺啟動Activity
最近有個需求:在檢查到特定條件的時候,自動從後臺啟動頁面。
很簡單的功能,但是也遇到了坑,那就是:按Home鍵時無法從後臺啟動Activity。
會報以下錯誤:
10-22 17:31:21.897 I/ActivityManager(664): START u0 {flg=0x14000000 meizuflg=0x200000 cmp=com.pl.getaway.getaway/com.pl.getaway.component.Activity.welcome.SplashActivity } from uid 10255 10-22 17:31:21.897 W/ActivityManager(664): Activity start request from 10020 stopped
百度一下,很快就找到了原因,是Android系統本身的限制:
當通過 home 鍵將當前 activity 置於後臺時,任何在後臺startActivity 的操作都將會延遲 5 秒。 除非該應用獲取了"android.permission.STOP_APP_SWITCHES" 許可權。 關於延遲 5 秒的操作在 com.android.server.am.ActivityManagerService 中的 stopAppSwitches() 方法中。 系統級的應用當獲取了 "android.permission.STOP_APP_SWITCHES" 後將不會呼叫到這個方法來延遲通過後臺啟動 activity 的操作。 事實上 android 原生的 Phone 應用就是這樣的情況,它是一個獲取了"android.permission.STOP_APP_SWITCHES" 許可權的系統級應用。 當有來電時,一個從後臺啟動的 activity 將突然出現在使用者的面前,警醒使用者有新的來電,這樣的設計是合理的。
參考自——ofollow,noindex">後臺啟動Activity
原因是知道了,但是是文中卻沒有給出可行的解決辦法。但我們怎麼能就此放棄呢。經過一番搜尋,終於在sof上找到了答案:Starting an activity from a service after HOME button pressed without the 5 seconds delay
把:
Intent intent = new Intent(context, A.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent);
改成:
Intent intent = new Intent(context, A.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); try { pendingIntent.send(); } catch (PendingIntent.CanceledException e) { e.printStackTrace(); }
如此即可解決問題。
但是這種方案也並不完美,在pixel 2 android 9上可以完美執行,但是在小米6 miui10,android 8.0上無法執行。
再次感嘆:
1、面向google和sof程式設計是如此重要。
2、國產ROM是多麼厲害