Android 12(S) 行为变更适配

7,107 阅读2分钟

Android 12已经到了Beta阶段,应用也差不多要开始适配 Android 12了。 下面把Android S的主要适配项列出
影响范围:targetSDKVersion为Android 12的应用。

一、exported属性

在旧版本中只要声明了Intent-filter属性的组件exported默认为true。 而在Android S则需要在包含Intent-filter的组件显性的声明exported属性。

如果不声明exported属性,在Android Studio上安装apk到Android 12的机器上会显示以下错误。当出现以下错误时就需要看看Manifest中的导出组件是否都声明了exported属性。

Installation did not succeed.
The application could not be installed: INSTALL_FAILED_VERIFICATION_FAILURE

其实这一项适配工作并不多,难的是三方sdk的导出组件需要适配

二、pendingIntent必须声明可变性

如需声明特定 PendingIntent 对象是否可变,请分别使用 PendingIntent.FLAG_MUTABLE 或 PendingIntent.FLAG_IMMUTABLE 标志。如果您的应用试图在不设置任何可变标志的情况下创建 PendingIntent 对象,系统会抛出 IllegalArgumentException

PACKAGE_NAME: Targeting S+ (version 10000 and above) requires that one of \
FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.

Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if \
some functionality depends on the PendingIntent being mutable, e.g. if \
it needs to be used with inline replies or bubbles.

适配的例子:之前

PendingIntent pendingActivityIntent = PendingIntent.getActivity(Application.getContext(), R.drawable.ic_launcher, intent,
PendingIntent.FLAG_ONE_SHOT);

Android 12及之后

PendingIntent pendingActivityIntent = PendingIntent.getActivity(Application.getContext(), R.drawable.ic_launcher, intent,
PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);

三、在后台启动前台服务的限制

除了少数情况外,应用无法在处于后台时启动前台服务。

例外情况

四、无法通过服务或广播接收器创建通知 trampoline

以 Android 12 为目标平台的应用无法从用作通知 trampoline 的服务或广播接收器中启动 activity。换言之,当用户点按通知或通知中的操作按钮时,您的应用无法在服务或广播接收器内调用 startActivity()。 系统会阻止这样的启动,并且会打印log

Indirect notification activity start (trampoline) from PACKAGE_NAME, \
this should be avoided for performance reasons.

迁移方式:使用PendingIntent

[1]行为变更:以 Android 12 为目标平台的应用