Cambiamenti del comportamento: app destinate ad Android 14 o versioni successive

Come le release precedenti, Android 14 include modifiche al comportamento che potrebbero influire sulla tua app. Le seguenti modifiche al comportamento si applicano esclusivamente alle app che hanno come target Android 14 (livello API 34) o versioni successive. Se la tua app ha come target Android 14 o versioni successive, devi modificarla in modo da supportare correttamente questi comportamenti, ove applicabile.

Assicurati di esaminare anche l'elenco delle modifiche al comportamento che interessano tutte le app in esecuzione su Android 14, indipendentemente dal targetSdkVersion dell'app.

Funzionalità di base

I tipi di servizi in primo piano sono obbligatori

如果您的应用以 Android 14(API 级别 34)或更高版本为目标平台,则必须为应用中的每个前台服务至少指定一项前台服务类型。您应选择一个能代表应用用例的前台服务类型。系统需要特定类型的前台服务满足特定用例。

如果应用中的用例与这些类型均不相关,强烈建议您迁移逻辑以使用 WorkManager用户发起的数据传输作业

Applicazione dell'autorizzazione BLUETOOTH_CONNECT in 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" />

Aggiornamenti di OpenJDK 17

Android 14 continua l'opera di aggiornamento delle librerie di base di Android per allinearsi alle funzionalità delle ultime release OpenJDK LTS, inclusi gli aggiornamenti delle librerie e il supporto del linguaggio Java 17 per gli sviluppatori di app e piattaforme.

Alcune di queste modifiche possono influire sulla compatibilità delle app:

  • Modifiche alle espressioni regolari: i riferimenti ai gruppi non validi ora non sono consentiti per seguire più da vicino la semantica di OpenJDK. Potresti vedere nuovi casi in cui viene generato un IllegalArgumentException dalla classe java.util.regex.Matcher, quindi assicurati di testare la tua app per verificare la presenza di aree che utilizzano espressioni regolari. Per attivare o disattivare questa modifica durante il test, attiva/disattiva il flag DISALLOW_INVALID_GROUP_REFERENCE utilizzando gli strumenti del framework di compatibilità.
  • Gestione degli UUID: il metodo java.util.UUID.fromString() ora esegue controlli più rigorosi durante la convalida dell'argomento di input, pertanto potresti visualizzare un IllegalArgumentException durante la deserializzazione. Per attivare o disattivare questa variazione durante il test, attiva/disattiva il flag ENABLE_STRICT_VALIDATION utilizzando gli strumenti del framework di compatibilità.
  • Problemi di ProGuard: in alcuni casi, l'aggiunta della classe java.lang.ClassValue causa un problema se provi a ridurre, offuscare e ottimizzare l'app utilizzando ProGuard. Il problema ha origine da una libreria Kotlin che modifica il comportamento di runtime in base al fatto che Class.forName("java.lang.ClassValue") restituisca o meno una classe. Se la tua app è stata sviluppata in base a una versione precedente del runtime senza la classe java.lang.ClassValue disponibile, queste ottimizzazioni potrebbero rimuovere il metodo computeValue dalle classi derivate da java.lang.ClassValue.

JobScheduler rafforza il comportamento di callback e rete

自从引入后,JobScheduler 期望您的应用从 onStartJobonStopJob。在 Android 14 之前,如果作业运行时间过长,系统会停止作业并静默失败。如果您的应用以 Android 14(API 级别 34)或更高版本为目标平台, 超过在主线程上授予的时间,应用会触发 ANR 显示“没有响应 onStartJob”错误消息或 “onStopJob没有回复”。

此 ANR 可能是由以下 2 种情况造成的: 1.有工作阻塞主线程,阻止回调 onStartJob 或者onStopJob在预期时间内执行并完成。 2. 开发者在 JobScheduler 中运行阻塞工作 回调 onStartJobonStopJob,阻止从 在预期的时限内完成

要解决第 1 个问题,您需要进一步调试阻塞主线程的因素 您可以使用以下代码 ApplicationExitInfo#getTraceInputStream(),用于获取 Tombstone ANR 发生时的跟踪信息如果您能够手动重现 ANR 问题 您可以录制系统轨迹,并使用 Android StudioPerfetto,以便更好地了解应用上运行的 在发生 ANR 时调用主线程 请注意,直接使用 JobScheduler API 或使用 androidx 库 WorkManager 时可能会发生这种情况。

如需解决问题 2,请考虑迁移到 WorkManager,它支持将 onStartJobonStopJob 中的任何处理封装在异步线程中。

JobScheduler 还引入了一项要求,即如果使用 setRequiredNetworkTypesetRequiredNetwork 约束条件,则必须声明 ACCESS_NETWORK_STATE 权限。如果您的应用未声明 ACCESS_NETWORK_STATE 权限 Android 14 或更高版本,则会导致 SecurityException

API di lancio di Tiles

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

Privacy

Accesso parziale a foto e video

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.

Esperienza utente

Notifiche di intent a schermo intero sicure

在 Android 11(API 级别 30)中,任何应用都可以在手机处于锁定状态时使用 Notification.Builder.setFullScreenIntent 发送全屏 intent。您可以通过在 AndroidManifest 中声明 USE_FULL_SCREEN_INTENT 权限,在应用安装时自动授予此权限。

全屏 intent 通知适用于需要用户立即注意的极高优先级通知,例如用户来电或用户配置的闹钟设置。对于以 Android 14(API 级别 34)或更高版本为目标平台的应用,获准使用此权限的应用仅限于提供通话和闹钟的应用。对于不适合此情况的任何应用,Google Play 商店会撤消其默认的 USE_FULL_SCREEN_INTENT 权限。这些政策变更的截止日期为 2024 年 5 月 31 日

在用户更新到 Android 14 之前,在手机上安装的应用仍拥有此权限。用户可以开启和关闭此权限。

您可以使用新 API NotificationManager.canUseFullScreenIntent 检查应用是否具有该权限;如果没有,应用可以使用新 intent ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT 启动设置页面,在该页面中,用户可以授予权限。

Sicurezza

Restrizioni agli intenti impliciti e in attesa

对于以 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);

I broadcast receiver registrati in fase di runtime devono specificare il comportamento di esportazione

以 Android 14(API 级别 34)或更高版本为目标平台并使用上下文注册的接收器的应用和服务必须指定以下标志,以指明接收器是否应导出到设备上的所有其他应用:RECEIVER_EXPORTEDRECEIVER_NOT_EXPORTED。此要求有助于利用 Android 13 中引入的这些接收器的功能,来保护应用免受安全漏洞的影响。

仅接收系统广播的接收器的例外情况

如果您的应用仅通过 Context#registerReceiver 方法(例如 Context#registerReceiver())针对系统广播注册接收器,那么它在注册接收器时不应指定标志。

Caricamento di codice dinamico più sicuro

If your app targets Android 14 (API level 34) or higher and uses Dynamic Code Loading (DCL), all dynamically-loaded files must be marked as read-only. Otherwise, the system throws an exception. We recommend that apps avoid dynamically loading code whenever possible, as doing so greatly increases the risk that an app can be compromised by code injection or code tampering.

If you must dynamically load code, use the following approach to set the dynamically-loaded file (such as a DEX, JAR, or APK file) as read-only as soon as the file is opened and before any content is written:

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);

Handle dynamically-loaded files that already exist

To prevent exceptions from being thrown for existing dynamically-loaded files, we recommend deleting and recreating the files before you try to dynamically load them again in your app. As you recreate the files, follow the preceding guidance for marking the files read-only at write time. Alternatively, you can re-label the existing files as read-only, but in this case, we strongly recommend that you verify the integrity of the files first (for example, by checking the file's signature against a trusted value), to help protect your app from malicious actions.

Ulteriori limitazioni relative all'avvio di attività in background

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

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

Zip Path Traversal

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

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

Per le app che hanno come target Android 14 (livello API 34) o versioni successive, un SecurityException viene generato da MediaProjection#createVirtualDisplay in uno dei seguenti scenari:

L'app deve chiedere all'utente di dare il consenso prima di ogni sessione di acquisizione. Una singola sessione di acquisizione è una singola chiamata su MediaProjection#createVirtualDisplay e ogni istanza di MediaProjection deve essere utilizzata una sola volta.

Gestire le modifiche alla configurazione

Se la tua app deve richiamare MediaProjection#createVirtualDisplay per gestire le modifiche alla configurazione (ad esempio l'orientamento o le dimensioni dello schermo), puoi seguire questi passaggi per aggiornare VirtualDisplay per l'istanza MediaProjection esistente:

  1. Richiama VirtualDisplay#resize con la nuova larghezza e altezza.
  2. Fornisci un nuovo Surface con le nuove larghezza e altezza a VirtualDisplay#setSurface.

Registra un callback

L'app deve registrare un callback per gestire i casi in cui l'utente non concede il consenso per continuare una sessione di acquisizione. Per farlo, implementa Callback#onStop e fai in modo che la tua app rilasci le risorse correlate (come VirtualDisplay e Surface).

Se la tua app non registra questo callback,MediaProjection#createVirtualDisplay genera un IllegalStateException quando la tua app lo invoca.

Limitazioni non SDK aggiornate

Android 14 include elenchi aggiornati di interfacce non SDK limitate in base alla collaborazione con gli sviluppatori Android e ai più recenti test interni. Ove possibile, ci assicuriamo che siano disponibili alternative pubbliche prima di applicare limitazioni alle interfacce non SDK.

Se la tua app non ha come target Android 14, alcune di queste modifiche potrebbero non interessarti immediatamente. Tuttavia, anche se al momento puoi utilizzare alcune interfacce non SDK (a seconda del livello API target della tua app), l'utilizzo di qualsiasi metodo o campo non SDK comporta sempre un rischio elevato di interrompere la tua app.

Se non sai con certezza se la tua app utilizza interfacce non SDK, puoi testarla per scoprirlo. Se la tua app si basa su interfacce non SDK, devi iniziare a pianificare la migrazione a alternative SDK. Tuttavia, siamo consapevoli che alcune app hanno casi d'uso validi per l'utilizzo di interfacce non SDK. Se non riesci a trovare un'alternativa all'utilizzo di un'interfaccia non SDK per una funzionalità nella tua app, devi richiedere una nuova API pubblica.

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