Android10适配-针对从后台启动 Activity 的限制

Android 10 中的隐私权变更

从 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 适配攻略

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