Modifications de comportement : applications ciblant Android 14 ou version ultérieure

Comme les versions précédentes, Android 14 apporte des modifications de comportement pouvant affecter votre application. Les modifications de comportement suivantes s'appliquent exclusivement aux applications qui ciblent Android 14 (niveau d'API 34) ou version ultérieure. Si votre application cible Android 14 ou une version ultérieure, vous devez la modifier pour qu'elle prenne en charge ces comportements, le cas échéant.

Veillez également à consulter la liste des modifications de comportement qui affectent toutes les applications exécutées sur Android 14, peu importe la targetSdkVersion de l'application.

Fonctionnalité de base

Le type de service au premier plan doit être indiqué

Si votre application cible Android 14 (niveau d'API 34) ou version ultérieure, elle doit spécifier au moins un type de service de premier plan pour chaque service de premier plan dans votre application. Vous devez choisir un type de service de premier plan qui représente le cas d'utilisation de votre application. Le système s'attend à ce que des services de premier plan présentant un type particulier répondent à un cas d'utilisation particulier.

Si un cas d'utilisation dans votre application n'est associé à aucun de ces types, il est fortement recommandé de migrer votre logique pour utiliser WorkManager ou les tâches de transfert de données déclenchées par l'utilisateur.

Application de l'autorisation BLUETOOTH_CONNECT dans BluetoothAdapter

Android 14 enforces the BLUETOOTH_CONNECT permission when calling the BluetoothAdapter getProfileConnectionState() method for apps targeting Android 14 (API level 34) or higher.

This method already required the BLUETOOTH_CONNECT permission, but it was not enforced. Make sure your app declares BLUETOOTH_CONNECT in your app's AndroidManifest.xml file as shown in the following snippet and check that a user has granted the permission before calling getProfileConnectionState.

<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

Mises à jour OpenJDK 17

Android 14 将继续更新 Android 的核心库,以与最新 OpenJDK LTS 版本中的功能保持一致,包括适合应用和平台开发者的库更新和 Java 17 语言支持。

以下变更可能会影响应用兼容性:

  • 对正则表达式的更改:现在,为了更严格地遵循 OpenJDK 的语义,不允许无效的组引用。您可能会看到 java.util.regex.Matcher 类抛出 IllegalArgumentException 的新情况,因此请务必测试应用中使用正则表达式的情形。如需在测试期间启用或停用此变更,请使用兼容性框架工具切换 DISALLOW_INVALID_GROUP_REFERENCE 标志。
  • UUID 处理:现在,验证输入参数时,java.util.UUID.fromString() 方法会执行更严格的检查,因此您可能会在反序列化期间看到 IllegalArgumentException。如需在测试期间启用或停用此变更,请使用兼容性框架工具切换 ENABLE_STRICT_VALIDATION 标志。
  • ProGuard 问题:有时,在您尝试使用 ProGuard 缩减、混淆和优化应用时,添加 java.lang.ClassValue 类会导致问题。问题源自 Kotlin 库,该库会根据 Class.forName("java.lang.ClassValue") 是否会返回类更改运行时行为。如果您的应用是根据没有 java.lang.ClassValue 类的旧版运行时开发的,则这些优化可能会将 computeValue 方法从派生自 java.lang.ClassValue 的类中移除。

JobScheduler renforce le comportement des rappels et du réseau

Since its introduction, JobScheduler expects your app to return from onStartJob or onStopJob within a few seconds. Prior to Android 14, if a job runs too long, the job is stopped and fails silently. If your app targets Android 14 (API level 34) or higher and exceeds the granted time on the main thread, the app triggers an ANR with the error message "No response to onStartJob" or "No response to onStopJob".

This ANR may be a result of 2 scenarios: 1. There is work blocking the main thread, preventing the callbacks onStartJob or onStopJob from executing and completing within the expected time limit. 2. The developer is running blocking work within the JobScheduler callback onStartJob or onStopJob, preventing the callback from completing within the expected time limit.

To address #1, you will need to further debug what is blocking the main thread when the ANR occurs, you can do this using ApplicationExitInfo#getTraceInputStream() to get the tombstone trace when the ANR occurs. If you're able to manually reproduce the ANR, you can record a system trace and inspect the trace using either Android Studio or Perfetto to better understand what is running on the main thread when the ANR occurs. Note that this can happen when using JobScheduler API directly or using the androidx library WorkManager.

To address #2, consider migrating to WorkManager, which provides support for wrapping any processing in onStartJob or onStopJob in an asynchronous thread.

JobScheduler also introduces a requirement to declare the ACCESS_NETWORK_STATE permission if using setRequiredNetworkType or setRequiredNetwork constraint. If your app does not declare the ACCESS_NETWORK_STATE permission when scheduling the job and is targeting Android 14 or higher, it will result in a SecurityException.

API de lancement des tuiles

对于以 Android 14 及更高版本为目标平台的应用, TileService#startActivityAndCollapse(Intent) 已弃用,现在会抛出 调用时抛出异常。如果您的应用从功能块启动 activity,请使用 TileService#startActivityAndCollapse(PendingIntent)

Confidentialité

Accès limité aux photos et aux vidéos

Android 14 introduces Selected Photos Access, which allows users to grant apps access to specific images and videos in their library, rather than granting access to all media of a given type.

This change is only enabled if your app targets Android 14 (API level 34) or higher. If you don't use the photo picker yet, we recommend implementing it in your app to provide a consistent experience for selecting images and videos that also enhances user privacy without having to request any storage permissions.

If you maintain your own gallery picker using storage permissions and need to maintain full control over your implementation, adapt your implementation to use the new READ_MEDIA_VISUAL_USER_SELECTED permission. If your app doesn't use the new permission, the system runs your app in a compatibility mode.

Expérience utilisateur

Notifications d'intent plein écran sécurisées

Avec Android 11 (niveau d'API 30), toutes les applications pouvaient utiliser Notification.Builder.setFullScreenIntent pour envoyer des intents plein écran lorsque le téléphone était verrouillé. Vous pouvez l'accorder automatiquement lors de l'installation de l'application en déclarant l'autorisation USE_FULL_SCREEN_INTENT dans le fichier AndroidManifest.

Les notifications d'intent plein écran sont conçues pour les notifications à priorité très élevée nécessitant l'attention immédiate de l'utilisateur, comme les appels entrants ou les paramètres d'alarme configurés par l'utilisateur. Pour les applications ciblant Android 14 (niveau d'API 34) ou version ultérieure, seules les applications qui proposent des fonctionnalités d'appel et d'alarmes peuvent utiliser cette autorisation. Le Google Play Store révoque les autorisations USE_FULL_SCREEN_INTENT par défaut pour toutes les applications qui ne correspondent pas à ce profil. La date limite pour appliquer ces modifications est le 31 mai 2024.

Cette autorisation reste activée pour les applications installées sur le téléphone avant que l'utilisateur passe à Android 14. Les utilisateurs peuvent activer et désactiver cette autorisation.

Vous pouvez utiliser la nouvelle API NotificationManager.canUseFullScreenIntent pour vérifier si votre application dispose de l'autorisation. Sinon, votre application peut utiliser le nouvel intent ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT pour afficher la page des paramètres où les utilisateurs peuvent accorder l'autorisation.

Sécurité

Restrictions concernant les intents implicites et en attente

对于以 Android 14(API 级别 34)或更高版本为目标平台的应用,Android 会通过以下方式限制应用向内部应用组件发送隐式 intent:

  • 隐式 intent 只能传送到导出的组件。应用必须使用显式 intent 传送到未导出的组件,或将该组件标记为已导出。
  • 如果应用通过未指定组件或软件包的 intent 创建可变待处理 intent,系统会抛出异常。

这些变更可防止恶意应用拦截意在供应用内部组件使用的隐式 intent。

例如,下面是可以在应用的清单文件中声明的 intent 过滤器

<activity
    android:name=".AppActivity"
    android:exported="false">
    <intent-filter>
        <action android:name="com.example.action.APP_ACTION" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

如果应用尝试使用隐式 intent 启动此 activity,则系统会抛出 ActivityNotFoundException 异常:

Kotlin

// Throws an ActivityNotFoundException exception when targeting Android 14.
context.startActivity(Intent("com.example.action.APP_ACTION"))

Java

// Throws an ActivityNotFoundException exception when targeting Android 14.
context.startActivity(new Intent("com.example.action.APP_ACTION"));

如需启动非导出的 activity,应用应改用显式 intent:

Kotlin

// This makes the intent explicit.
val explicitIntent =
        Intent("com.example.action.APP_ACTION")
explicitIntent.apply {
    package = context.packageName
}
context.startActivity(explicitIntent)

Java

// This makes the intent explicit.
Intent explicitIntent =
        new Intent("com.example.action.APP_ACTION")
explicitIntent.setPackage(context.getPackageName());
context.startActivity(explicitIntent);

Les broadcasts receivers enregistrés lors de l'exécution doivent spécifier le comportement d'exportation

Les applications et les services qui ciblent Android 14 (niveau d'API 34) ou version ultérieure et utilisent des récepteurs enregistrés en contexte doivent spécifier un indicateur pour indiquer si le récepteur doit être, ou non, exporté vers toutes les autres applications de l'appareil: RECEIVER_EXPORTED ou RECEIVER_NOT_EXPORTED, respectivement. Cette exigence permet de protéger les applications contre les failles de sécurité en tirant parti des fonctionnalités pour ces récepteurs introduites dans Android 13.

Exception pour les récepteurs qui ne reçoivent que des annonces du système

Si votre application n'enregistre un récepteur que pour les annonces du système via les méthodes Context#registerReceiver, telles que Context#registerReceiver(), aucun indicateur ne doit être spécifié lors de l'enregistrement du récepteur.

Chargement de code dynamique plus sécurisé

如果您的应用以 Android 14(API 级别 34)或更高版本为目标平台并使用动态代码 正在加载 (DCL),所有动态加载的文件都必须标记为只读。 否则,系统会抛出异常。我们建议应用尽可能避免动态加载代码,因为这样做会大大增加应用因代码注入或代码篡改而遭到入侵的风险。

如果必须动态加载代码,请使用以下方法,在动态文件(例如 DEX、JAR 或 APK 文件)打开并写入任何内容之前立即将其设为只读:

Kotlin

val jar = File("DYNAMICALLY_LOADED_FILE.jar")
val os = FileOutputStream(jar)
os.use {
    // Set the file to read-only first to prevent race conditions
    jar.setReadOnly()
    // Then write the actual file content
}
val cl = PathClassLoader(jar, parentClassLoader)

Java

File jar = new File("DYNAMICALLY_LOADED_FILE.jar");
try (FileOutputStream os = new FileOutputStream(jar)) {
    // Set the file to read-only first to prevent race conditions
    jar.setReadOnly();
    // Then write the actual file content
} catch (IOException e) { ... }
PathClassLoader cl = new PathClassLoader(jar, parentClassLoader);

处理已存在的动态加载文件

为防止系统对现有动态加载的文件抛出异常,我们建议您先删除并重新创建文件,然后再尝试在应用中重新动态加载这些文件。重新创建文件时,请按照上述指南在写入时将文件标记为只读。或者,您可以将现有文件重新标记为只读,但在这种情况下,我们强烈建议您先验证文件的完整性(例如,对照可信值检查文件的签名)以保护应用免遭恶意操作的影响。

Restrictions supplémentaires concernant le démarrage d'activités en arrière-plan

对于以 Android 14(API 级别 34)或更高版本为目标平台的应用,系统会进一步限制允许应用在后台启动 activity 的时间:

这些更改扩大了一组现有限制条件的范围,目的是防止恶意应用滥用 API 以在后台启动干扰性活动,从而保护用户。

Traversée de répertoire ZIP

对于以 Android 14(API 级别 34)或更高版本为目标平台的应用,Android 会通过以下方式防止 Zip 路径遍历漏洞:如果 Zip 文件条目名称包含“..”或以“/”开头,ZipFile(String)ZipInputStream.getNextEntry() 会抛出 ZipException

应用可以通过调用 dalvik.system.ZipPathValidator.clearCallback() 选择停用此验证。

Pour les applications ciblant Android 14 (niveau d'API 34) ou version ultérieure, une exception SecurityException est générée par MediaProjection#createVirtualDisplay dans l'un des scénarios suivants:

Votre application doit demander à l'utilisateur de donner son consentement avant chaque session de capture. Une session de capture unique correspond à une seule invocation sur MediaProjection#createVirtualDisplay, et chaque instance MediaProjection ne doit être utilisée qu'une seule fois.

Gérer les modifications de configuration

Si votre application doit appeler MediaProjection#createVirtualDisplay pour gérer les modifications de configuration (telles que l'orientation ou la taille de l'écran), vous pouvez suivre ces étapes pour mettre à jour VirtualDisplay pour l'instance MediaProjection existante:

  1. Appelez VirtualDisplay#resize avec la nouvelle largeur et la nouvelle hauteur.
  2. Fournissez un nouvel élément Surface avec la nouvelle largeur et la nouvelle hauteur à VirtualDisplay#setSurface.

Enregistrer un rappel

Votre application doit enregistrer un rappel pour gérer les cas où l'utilisateur ne donne pas son autorisation pour poursuivre une session de capture. Pour ce faire, implémentez Callback#onStop et demandez à votre application de libérer toutes les ressources associées (telles que VirtualDisplay et Surface).

Si votre application n'enregistre pas ce rappel, MediaProjection#createVirtualDisplay génère une exception IllegalStateException lorsque votre application l'appelle.

Mise à jour des restrictions non SDK

Android 14 inclut des listes à jour d'interfaces non SDK limitées grâce à la collaboration avec les développeurs Android et aux derniers tests internes. Dans la mesure du possible, nous nous assurons que des alternatives publiques sont disponibles avant de limiter les interfaces non SDK.

Si votre application ne cible pas Android 14, certaines de ces modifications ne vous affecteront peut-être pas immédiatement. Cependant, bien que vous puissiez actuellement utiliser certaines interfaces non SDK (en fonction du niveau d'API cible de votre application), l'utilisation d'un champ ou d'une méthode non SDK présente toujours un risque élevé d'endommager votre application.

Si vous n'êtes pas sûr que votre application utilise des interfaces non SDK, vous pouvez tester votre application pour le savoir. Si votre application repose sur des interfaces non SDK, vous devriez commencer à planifier une migration vers des alternatives SDK. Nous comprenons néanmoins que certaines applications ont des cas d'utilisation valides pour utiliser des interfaces non SDK. Si vous ne trouvez pas d'alternative à l'utilisation d'une interface non SDK pour une fonctionnalité de votre application, vous devriez demander une nouvelle API publique.

如需详细了解此 Android 版本中的变更,请参阅 Android 14 中有关限制非 SDK 接口的更新。如需全面了解有关非 SDK 接口的详细信息,请参阅对非 SDK 接口的限制