Podobnie jak w przypadku poprzednich wersji, Android 14 zawiera zmiany działania, które mogą mieć wpływ na Twoją aplikację. Poniższe zmiany działania mają zastosowanie wyłącznie do aplikacji kierowanych na Androida 14 (poziom API 34) lub nowszego. Jeśli Twoja aplikacja jest kierowana na Androida 14 lub nowszą wersję, w odpowiednich przypadkach zmodyfikuj ją, aby obsługiwała te funkcje.
Zapoznaj się też z listą zmian w zachowaniu, które wpływają na wszystkie aplikacje działające na Androidzie 14, niezależnie od ich targetSdkVersion
.
Główna funkcja
Wymagane są typy usług działających na pierwszym planie
如果您的应用以 Android 14(API 级别 34)或更高版本为目标平台,则必须为应用中的每个前台服务至少指定一项前台服务类型。您应选择一个能代表应用用例的前台服务类型。系统需要特定类型的前台服务满足特定用例。
如果应用中的用例与这些类型均不相关,强烈建议您迁移逻辑以使用 WorkManager 或用户发起的数据传输作业。
Wymuszanie uprawnienia BLUETOOTH_CONNECT w BluetoothAdapter
对于以 Android 14(API 级别 34)或更高版本为目标平台的应用,Android 14 会在调用 BluetoothAdapter
getProfileConnectionState()
方法时强制执行 BLUETOOTH_CONNECT
权限。
此方法已要求 BLUETOOTH_CONNECT
权限,但未强制执行。确保您的应用在应用的 AndroidManifest.xml
文件中声明 BLUETOOTH_CONNECT
,如以下代码段所示,并在调用 getProfileConnectionState
之前检查用户是否已授予相应权限。
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
aktualizacje 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
IllegalArgumentException
is thrown by thejava.util.regex.Matcher
class, 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_REFERENCE
flag 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 anIllegalArgumentException
during deserialization. To enable or disable this change while testing, toggle theENABLE_STRICT_VALIDATION
flag using the compatibility framework tools. - ProGuard issues: In some cases, the addition of the
java.lang.ClassValue
class 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.ClassValue
class available, then these optimizations might remove thecomputeValue
method from classes derived fromjava.lang.ClassValue
.
JobScheduler wzmacnia zachowanie wywołania zwrotnego i sieci
自从引入后,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
。
Interfejs API uruchamiania kafelków
For apps targeting 14 and higher,
TileService#startActivityAndCollapse(Intent)
is deprecated and now throws
an exception when called. If your app launches activities from tiles, use
TileService#startActivityAndCollapse(PendingIntent)
instead.
Prywatność
częściowy dostęp do zdjęć i filmów,
Android 14 引入了“已选照片访问权限”,让用户可以向应用授予对其媒体库中特定图片和视频的访问权限,而不是授予对给定类型的所有媒体的访问权限。
只有当您的应用以 Android 14(API 级别 34)或更高版本为目标平台时,此更改才会启用。如果您尚未使用照片选择器,我们建议您在应用中实现照片选择器,以提供一致的图片和视频选择体验,同时增强用户隐私保护,而无需请求任何存储权限。
如果您使用存储权限维护自己的图库选择器,并且需要对实现保持完全控制,请调整实现以使用新的 READ_MEDIA_VISUAL_USER_SELECTED
权限。如果您的应用不使用新权限,系统会以兼容模式运行您的应用。
Interfejs użytkownika
Bezpieczne powiadomienia pełnoekranowe o intencjach
With Android 11 (API level 30), it was possible for any app to use
Notification.Builder.setFullScreenIntent
to send full-screen
intents while the phone is locked. You could auto-grant this on app install by
declaring USE_FULL_SCREEN_INTENT
permission in the
AndroidManifest.
Full-screen intent notifications are designed for extremely high-priority
notifications demanding the user's immediate attention, such as an incoming
phone call or alarm clock settings configured by the user. For apps targeting
Android 14 (API level 34) or higher, apps that are allowed to use this
permission are limited to those that provide calling and alarms only. The Google
Play Store revokes default USE_FULL_SCREEN_INTENT
permissions for any apps
that don't fit this profile. The deadline for these policy changes is May 31,
2024.
This permission remains enabled for apps installed on the phone before the user updates to Android 14. Users can turn this permission on and off.
You can use the new API
NotificationManager.canUseFullScreenIntent
to check if your app
has the permission; if not, your app can use the new intent
ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT
to launch the settings
page where users can grant the permission.
Bezpieczeństwo
Ograniczenia intencji niewyrażonych i oczekujących
对于以 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);
Odbiorniki zarejestrowane w czasie działania muszą określać działanie dotyczące eksportu
Apps and services that target Android 14 (API level 34) or higher and use
context-registered receivers are required to specify a flag
to indicate whether or not the receiver should be exported to all other apps on
the device: either RECEIVER_EXPORTED
or RECEIVER_NOT_EXPORTED
, respectively.
This requirement helps protect apps from security vulnerabilities by leveraging
the features for these receivers introduced in Android 13.
Exception for receivers that receive only system broadcasts
If your app is registering a receiver only for
system broadcasts through Context#registerReceiver
methods, such as Context#registerReceiver()
, then it
shouldn't specify a flag when registering the receiver.
Bezpieczniejsze wczytywanie kodu dynamicznego
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.
Dodatkowe ograniczenia dotyczące rozpoczynania działań w tle
对于以 Android 14(API 级别 34)或更高版本为目标平台的应用,系统会进一步限制允许应用在后台启动 activity 的时间:
- 现在,当应用使用
PendingIntent#send()
或类似方法发送PendingIntent
时,如果它想要授予自己的后台 activity 启动待处理 intent 的启动特权,则必须选择启用。如需选择启用,应用应通过setPendingIntentBackgroundActivityStartMode(MODE_BACKGROUND_ACTIVITY_START_ALLOWED)
传递ActivityOptions
软件包。 - 当可见应用使用
bindService()
方法绑定其他在后台应用的服务时,如果可见应用想要授予自己的后台 activity 对绑定服务的启动特权,则必须选择启用。如需选择启用,应用应在调用bindService()
方法时包含BIND_ALLOW_ACTIVITY_STARTS
标志。
这些更改扩大了一组现有限制条件的范围,目的是防止恶意应用滥用 API 以在后台启动干扰性活动,从而保护用户。
Przemierzanie ścieżki ZIP
W przypadku aplikacji kierowanych na Androida 14 (poziom API 34) lub nowszego Android zapobiega podatności na atak polegający na przemierzaniu ścieżki w pliku ZIP w następujący sposób:
ZipFile(String)
i ZipInputStream.getNextEntry()
zgłaszaZipException
błąd, jeśli nazwy elementów pliku ZIP zawierają „..” lub zaczynają się od „/”.
Aplikacje mogą zrezygnować z tej weryfikacji, wywołując funkcję dalvik.system.ZipPathValidator.clearCallback()
.
Wymagana zgoda użytkownika w przypadku każdej sesji rejestrowania MediaProjection
对于以 Android 14(API 级别 34)或更高版本为目标平台的应用,在以下任一情况下,MediaProjection#createVirtualDisplay
都会抛出 SecurityException
:
- 您的应用会缓存从
MediaProjectionManager#createScreenCaptureIntent
返回的Intent
,并多次将其传递给MediaProjectionManager#getMediaProjection
。 - 您的应用在同一
MediaProjection
实例上多次调用MediaProjection#createVirtualDisplay
。
您的应用必须在每次捕获会话之前征求用户同意。单次捕获会话是对 MediaProjection#createVirtualDisplay
的单次调用,并且每个 MediaProjection
实例只能使用一次。
处理配置变更
如果您的应用需要调用 MediaProjection#createVirtualDisplay
来处理配置更改(例如屏幕方向或屏幕大小更改),您可以按照以下步骤更新现有 MediaProjection
实例的 VirtualDisplay
:
- 使用新的宽度和高度调用
VirtualDisplay#resize
。 - 向
VirtualDisplay#setSurface
提供新的Surface
,并为其指定新的宽度和高度。
注册回调
您的应用应注册回调,以处理用户不同意继续拍摄会话的情况。为此,请实现 Callback#onStop
,并让应用释放所有相关资源(例如 VirtualDisplay
和 Surface
)。
如果您的应用未注册此回调,当您的应用调用它时,MediaProjection#createVirtualDisplay
会抛出 IllegalStateException
。
Zaktualizowane ograniczenia inne niż związane z pakietem SDK
Android 14 zawiera zaktualizowane listy interfejsów innych niż skodyfikowane, które zostały ograniczone na podstawie współpracy z deweloperami Androida i najnowszych testów wewnętrznych. Zawsze, gdy to możliwe, sprawdzamy, czy istnieją publiczne alternatywy, zanim zaczniemy ograniczać interfejsy inne niż SDK.
Jeśli Twoja aplikacja nie jest kierowana na Androida 14, niektóre z tych zmian mogą nie mieć na Ciebie natychmiastowego wpływu. Obecnie możesz używać niektórych interfejsów spoza pakietu SDK (w zależności od docelowego poziomu interfejsu API aplikacji), ale korzystanie z metod lub pól spoza pakietu SDK zawsze wiąże się z wysokim ryzykiem awarii aplikacji.
Jeśli nie masz pewności, czy Twoja aplikacja używa interfejsów innych niż SDK, możesz przetestować ją, aby się tego dowiedzieć. Jeśli Twoja aplikacja korzysta z interfejsów spoza pakietu SDK, zacznij planować migrację do alternatyw dla pakietu SDK. Zdajemy sobie jednak sprawę, że w niektórych przypadkach interfejsy inne niż SDK mogą być przydatne. Jeśli nie możesz znaleźć alternatywy dla interfejsu spoza pakietu SDK, który jest używany w funkcji Twojej aplikacji, poproś o nowy interfejs publiczny API.
如需详细了解此 Android 版本中的变更,请参阅 Android 14 中有关限制非 SDK 接口的更新。如需全面了解有关非 SDK 接口的详细信息,请参阅对非 SDK 接口的限制。