從 Android 10 開始,系統會增加針對從後臺啓動 Activity 的限制。此項行爲變更有助於最大限度地減少對用戶造成的中斷,並且可以讓用戶更好地控制其屏幕上顯示的內容。只要您的應用啓動 Activity 是因用戶互動直接引發的,該應用就極有可能不會受到這些限制的影響。
谷歌官方建議將從後臺啓動的Activity改爲顯示通知。還可以選擇提供全屏Intent。
以下以全屏Intent爲適配範圍。
1、影響範圍
以 Android 10 (API 級別 29)或更高版本爲目標平臺的應用
2、增加權限
如果應用以 Android 10 或更高版本爲目標平臺並使用涉及全屏 intent 的通知,則必須在應用的清單文件中請求 USE_FULL_SCREEN_INTENT 權限。這是普通權限,因此,系統會自動爲請求權限的應用授予此權限。
即在AndroidManifest.xml中增加USE_FULL_SCREEN_INTENT權限:
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT"/>
如果以 Android 10 或更高版本爲目標平臺的應用嘗試創建使用全屏 intent 的通知而未請求必要權限,則系統會忽略此全屏 intent 並輸出以下日誌消息:
Package your-package-name: Use of fullScreenIntent requires the USE_FULL_SCREEN_INTENT permission
3、創建全屏Intent
Intent fullScreenIntent = new Intent(this, CallActivity.class);
PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Incoming call")
.setContentText("(919) 555-1234")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_CALL)
// Use a full-screen intent only for the highest-priority alerts where you
// have an associated activity that you would like to launch after the user
// interacts with the notification. Also, if your app targets Android 10
// or higher, you need to request the USE_FULL_SCREEN_INTENT permission in
// order for the platform to invoke this notification.
.setFullScreenIntent(fullScreenPendingIntent, true);
Notification incomingCallNotification = notificationBuilder.build();
注意:創建通知時,請務必添加描述性標題和消息。
4、機型適配
(1)Android 10 適配攻略中提到部分機型直接設置setPriority無效(或者說以渠道優先級爲準)。
需要闖將通知渠道時將重要性設置爲IMPORTANCE_HIGH:
NotificationChannel channel = new NotificationChannel(channelId, "xxx", NotificationManager.IMPORTANCE_HIGH);
(2)Android 10(Api 29)新特性適配 - 禁止後臺啓動Activity中提到:
在華爲mate20(Api-28)上需要到設置中打開橫幅通知;原生Android Q上有效
參考文章:
官網:針對全屏 Intent 的權限變更;從後臺啓動 Activity 的限制;創建高優先級通知
Android 10(Api 29)新特性適配 - 禁止後臺啓動Activity
Android 10 適配攻略