Seperti rilis sebelumnya, Android 14 menyertakan perubahan perilaku yang mungkin memengaruhi aplikasi Anda. Perubahan perilaku berikut ini berlaku khusus bagi aplikasi yang menargetkan Android 14 (level API 34) atau yang lebih tinggi. Jika aplikasi Anda menargetkan Android 14 atau yang lebih tinggi, Anda harus memodifikasi aplikasi untuk mendukung perilaku ini dengan benar, jika berlaku.
Pastikan Anda juga meninjau daftar perubahan perilaku yang memengaruhi semua aplikasi yang berjalan di Android 14, terlepas dari targetSdkVersion aplikasi.
Fungsi inti
Jenis layanan latar depan wajib diisi
如果您的应用以 Android 14(API 级别 34)或更高版本为目标平台,则必须为应用中的每个前台服务至少指定一项前台服务类型。您应选择一个能代表应用用例的前台服务类型。系统需要特定类型的前台服务满足特定用例。
如果应用中的用例与这些类型均不相关,强烈建议您迁移逻辑以使用 WorkManager 或用户发起的数据传输作业。
Penerapan izin BLUETOOTH_CONNECT di BluetoothAdapter
对于以 Android 14(API 级别 34)或更高版本为目标平台的应用,在调用 BluetoothAdapter getProfileConnectionState() 方法时,Android 14 会强制执行 BLUETOOTH_CONNECT 权限。
此方法已需要 BLUETOOTH_CONNECT 权限,但未强制执行。确保您的应用在应用的 AndroidManifest.xml 文件中声明 BLUETOOTH_CONNECT,如以下代码段所示,并在调用 getProfileConnectionState 之前检查用户是否已授予相应权限。
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
Update OpenJDK 17
Android 14 continues the work of refreshing Android's core libraries to align with the features in the latest OpenJDK LTS releases, including both library updates and Java 17 language support for app and platform developers.
A few of these changes can affect app compatibility:
- Changes to regular expressions: Invalid group references are now
disallowed to more closely follow the semantics of OpenJDK. You might see
new cases where an
IllegalArgumentExceptionis thrown by thejava.util.regex.Matcherclass, so make sure to test your app for areas that use regular expressions. To enable or disable this change while testing, toggle theDISALLOW_INVALID_GROUP_REFERENCEflag using the compatibility framework tools. - UUID handling: The
java.util.UUID.fromString()method now does more strict checks when validating the input argument, so you might see anIllegalArgumentExceptionduring deserialization. To enable or disable this change while testing, toggle theENABLE_STRICT_VALIDATIONflag using the compatibility framework tools. - ProGuard issues: In some cases, the addition of the
java.lang.ClassValueclass causes an issue if you try to shrink, obfuscate, and optimize your app using ProGuard. The problem originates with a Kotlin library that changes runtime behaviour based on whetherClass.forName("java.lang.ClassValue")returns a class or not. If your app was developed against an older version of the runtime without thejava.lang.ClassValueclass available, then these optimizations might remove thecomputeValuemethod from classes derived fromjava.lang.ClassValue.
JobScheduler memperkuat perilaku callback dan jaringan
自从引入后,JobScheduler 期望您的应用从
onStartJob 或 onStopJob。在 Android 14 之前,如果作业运行时间过长,系统会停止作业并静默失败。如果您的应用以 Android 14(API 级别 34)或更高版本为目标平台,
超过在主线程上授予的时间,应用会触发 ANR
显示“没有响应 onStartJob”错误消息或
“onStopJob没有回复”。
此 ANR 可能是由以下 2 种情况造成的:
1.有工作阻塞主线程,阻止回调 onStartJob
或者onStopJob在预期时间内执行并完成。
2. 开发者在 JobScheduler 中运行阻塞工作
回调 onStartJob 或 onStopJob,阻止从
在预期的时限内完成
要解决第 1 个问题,您需要进一步调试阻塞主线程的因素
您可以使用以下代码
ApplicationExitInfo#getTraceInputStream(),用于获取 Tombstone
ANR 发生时的跟踪信息如果您能够手动重现 ANR 问题
您可以录制系统轨迹,并使用
Android Studio 或 Perfetto,以便更好地了解应用上运行的
在发生 ANR 时调用主线程
请注意,直接使用 JobScheduler API 或使用 androidx 库 WorkManager 时可能会发生这种情况。
如需解决问题 2,请考虑迁移到 WorkManager,它支持将 onStartJob 或 onStopJob 中的任何处理封装在异步线程中。
JobScheduler 还引入了一项要求,即如果使用 setRequiredNetworkType 或 setRequiredNetwork 约束条件,则必须声明 ACCESS_NETWORK_STATE 权限。如果您的应用未声明
ACCESS_NETWORK_STATE 权限
Android 14 或更高版本,则会导致 SecurityException。
API peluncuran kartu
Untuk aplikasi yang menargetkan 14 dan yang lebih tinggi,
TileService#startActivityAndCollapse(Intent) tidak digunakan lagi dan kini menampilkan
pengecualian saat dipanggil. Jika aplikasi Anda meluncurkan aktivitas dari kartu, gunakan
TileService#startActivityAndCollapse(PendingIntent) sebagai gantinya.
Privasi
Akses sebagian ke foto dan 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.
Pengalaman pengguna
Notifikasi Intent layar penuh yang aman
在 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 启动设置页面,在该页面中,用户可以授予权限。
Keamanan
Pembatasan ke intent yang implisit dan tertunda
Untuk aplikasi yang menargetkan Android 14 (API level 34) atau yang lebih tinggi, Android membatasi pengiriman intent implisit ke komponen aplikasi internal dengan cara berikut:
- Intent implisit hanya dikirim ke komponen yang diekspor. Aplikasi harus menggunakan intent eksplisit untuk mengirim ke komponen yang tidak diekspor, atau menandai komponen sebagai diekspor.
- Jika aplikasi membuat intent tertunda yang dapat berubah dengan intent yang tidak menentukan komponen atau paket, sistem akan menampilkan pengecualian.
Perubahan ini mencegah aplikasi berbahaya agar tidak mencegat intent implisit yang dimaksudkan untuk digunakan oleh komponen internal aplikasi.
Misalnya, berikut ini filter intent yang dapat dideklarasikan dalam file manifes aplikasi Anda:
<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>
Jika aplikasi Anda mencoba meluncurkan aktivitas ini menggunakan intent implisit, pengecualian ActivityNotFoundException akan ditampilkan:
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"));
Untuk meluncurkan aktivitas yang tidak diekspor, aplikasi Anda harus menggunakan intent eksplisit:
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);
Penerima siaran yang terdaftar runtime harus menentukan perilaku ekspor
以 Android 14(API 级别 34)或更高版本为目标平台并使用上下文注册的接收器的应用和服务必须指定以下标志,以指明接收器是否应导出到设备上的所有其他应用:RECEIVER_EXPORTED 或 RECEIVER_NOT_EXPORTED。此要求有助于利用 Android 13 中引入的这些接收器的功能,来保护应用免受安全漏洞的影响。
仅接收系统广播的接收器的例外情况
如果您的应用仅通过 Context#registerReceiver 方法(例如 Context#registerReceiver())针对系统广播注册接收器,那么它在注册接收器时不应指定标志。
Pemuatan kode dinamis yang lebih aman
如果您的应用以 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);
处理已存在的动态加载文件
为防止系统对现有动态加载的文件抛出异常,我们建议您先删除并重新创建文件,然后再尝试在应用中重新动态加载这些文件。重新创建文件时,请按照上述指南在写入时将文件标记为只读。或者,您可以将现有文件重新标记为只读,但在这种情况下,我们强烈建议您先验证文件的完整性(例如,对照可信值检查文件的签名)以保护应用免遭恶意操作的影响。
Batasan tambahan dalam memulai aktivitas dari latar belakang
Untuk aplikasi yang menargetkan Android 14 (API level 34) atau yang lebih tinggi, sistem akan lebih membatasi kapan aplikasi diizinkan untuk memulai aktivitas dari latar belakang:
- Saat mengirim
PendingIntentmenggunakanPendingIntent#send()atau metode serupa, aplikasi harus memilih ikut serta jika ingin memberikan hak istimewa peluncuran aktivitas latar belakangnya sendiri untuk memulai intent yang tertunda. Untuk ikut serta, aplikasi harus meneruskan paketActivityOptionsdengansetPendingIntentBackgroundActivityStartMode(MODE_BACKGROUND_ACTIVITY_START_ALLOWED). - Saat aplikasi yang terlihat mengikat layanan dari aplikasi lain yang ada di latar belakang
menggunakan metode
bindService(), aplikasi yang terlihat kini harus memilih ikut serta jika ingin memberikan hak istimewa peluncuran aktivitas latar belakangnya ke layanan terikat. Untuk ikut serta, aplikasi harus menyertakan flagBIND_ALLOW_ACTIVITY_STARTSsaat memanggil metodebindService().
Perubahan ini memperluas rangkaian pembatasan yang ada untuk melindungi pengguna dengan mencegah aplikasi berbahaya agar tidak menyalahgunakan API untuk memulai aktivitas yang mengganggu dari latar belakang.
Zip path traversal
Untuk aplikasi yang menargetkan Android 14 (API level 34) atau yang lebih tinggi, Android mencegah Kerentanan Zip
Path Traversal dengan cara berikut:
ZipFile(String) dan
ZipInputStream.getNextEntry() menampilkan
ZipException jika nama entri file zip berisi ".." atau dimulai
dengan "/".
Aplikasi dapat memilih untuk tidak mengikuti validasi ini dengan memanggil
dalvik.system.ZipPathValidator.clearCallback().
Izin pengguna diperlukan untuk setiap sesi pengambilan MediaProjection
For apps targeting Android 14 (API level 34) or higher, a SecurityException is
thrown by MediaProjection#createVirtualDisplay in either of the following
scenarios:
- Your app caches the
Intentthat is returned fromMediaProjectionManager#createScreenCaptureIntent, and passes it multiple times toMediaProjectionManager#getMediaProjection. - Your app invokes
MediaProjection#createVirtualDisplaymultiple times on the sameMediaProjectioninstance.
Your app must ask the user to give consent before each capture session. A single
capture session is a single invocation on
MediaProjection#createVirtualDisplay, and each MediaProjection instance must
be used only once.
Handle configuration changes
If your app needs to invoke MediaProjection#createVirtualDisplay to handle
configuration changes (such as the screen orientation or screen size changing),
you can follow these steps to update the VirtualDisplay for the existing
MediaProjection instance:
- Invoke
VirtualDisplay#resizewith the new width and height. - Provide a new
Surfacewith the new width and height toVirtualDisplay#setSurface.
Register a callback
Your app should register a callback to handle cases where the user doesn't grant
consent to continue a capture session. To do this, implement
Callback#onStop and have your app release any related resources (such as
the VirtualDisplay and Surface).
If your app doesn't register this callback,
MediaProjection#createVirtualDisplay throws an IllegalStateException
when your app invokes it.
Pembatasan non-SDK yang diperbarui
Android 14 menyertakan daftar terbaru antarmuka non-SDK yang dibatasi berdasarkan kolaborasi dengan developer Android dan pengujian internal terbaru. Jika memungkinkan, kami akan memastikan ketersediaan alternatif publik sebelum membatasi antarmuka non-SDK.
Jika aplikasi Anda tidak menargetkan Android 14, beberapa perubahan ini mungkin tidak langsung memengaruhi Anda. Namun, meskipun saat ini Anda dapat menggunakan beberapa antarmuka non-SDK (bergantung pada API level target aplikasi Anda), penggunaan metode atau kolom non-SDK tetap sangat berisiko merusak aplikasi Anda.
Jika tidak yakin apakah aplikasi Anda menggunakan antarmuka non-SDK atau tidak, Anda dapat menguji aplikasi untuk mencari tahu. Jika aplikasi Anda mengandalkan antarmuka non-SDK, sebaiknya mulailah merencanakan migrasi ke alternatif SDK. Meskipun begitu, kami paham bahwa beberapa aplikasi memiliki kasus penggunaan yang valid untuk menggunakan antarmuka non-SDK. Jika tidak dapat menemukan alternatif penggunaan antarmuka non-SDK untuk fitur dalam aplikasi Anda, sebaiknya minta API publik baru.
Untuk mempelajari perubahan dalam rilis Android ini lebih lanjut, baca Pembaruan pembatasan antarmuka non-SDK di Android 14. Untuk mempelajari lebih lanjut antarmuka non-SDK secara umum, baca Pembatasan antarmuka non-SDK.