Android 14 App Adaptation Guide

Android 14 application adaptation guide:https://dev.mi.com/distribute/doc/details?pId=1718

Android 14 features and changes list | Android Developers | Android Developers

1. Get Android 14

1.1 Google release schedule

https://developer.android.com/about/versions/14/overview#timeline

1.2 Xiaomi mobile phone upgrades to Android 14

Now Xiaomi 13, Xiaomi 13 Pro, and Xiaomi Pad 6 can flash the MIUI 14 developer preview version based on Android™ 14 Beta 1 through the link.
https://web.vip.miui.com/page/info/mio/mio/detail?postId=40403123&fromPathname=mioSingleBoard&app_version=dev.230112
It doesn’t matter if you don’t have the above equipment yet. We have provided you with sufficient cloud testing equipment to support the adaptation work of the majority of developers. For details on the cloud testing platform, please see: https://testit.miui.com/android_14 (Application for permission to use cloud testing platform: https://m.beehive.miui.com/Ooq42P35TPAIP -sZJT1EqA)

1.3 Google native machine upgrade to Android 14

Developers with Pixel series machines can directly upgrade via ota, or download image upgrades. For details, see the link:
https://developer.android.google.cn/about/ versions/14/download

1.4 Android emulator

In Android Studio, you can install the Android 14 SDK as follows:

  • Click Tools>SDK Manager.
  • In the "SDK Plateforms" tab, select Android 14.
  • In the "SDK Tools" tab, select Android SDK Build-Tools 34.

Click OK to install the SDK.

To access the Android 14 API and test your app's compatibility with Android 14, open the module-level build.gradle or build.gradle.kts files and update them with the values ​​for Android 14: How to set these values The format depends on the Android Gradle Plugin (AGP) version you are using.

Note: If you are not ready to fully support Android 14, you can still use debuggable apps, Android 14 devices, and theCompatibility Framework to perform app compatibility testing without changing your app to be compatible with or target the preview SDK.

2. New features and APIs

2.1 Application-level language preference

Android 14 extends the App-level language features introduced in Android 13 (API level 33):

  1. Automatically generate App's localeConfig: Starting with Android Studio Giraffe Canary 7 and AGP 8.1.0-alpha07, developers can configure their apps to automatically support each app's language preference. According to the project resources, the Android Gradle plugin generates a LocaleConfig file and adds a reference to it in the final AndroidManifest.xml, so there is no need to manually create or update the file. AGP uses the resources and library module dependencies in the App module's res folder to determine which locales to include in the LocaleConfig file.
  2. Dynamic update of the app's localeConfig: Use setOverrideLocaleConfig() and getOverrideLocaleConfig() in LocaleManager to dynamically update the App's supported language list in the device's system settings. Use this feature to customize the list of supported languages ​​per region, do A/B testing, or provide an updated list of locales if the app utilizes server-side push for localization.

Here we show an example of dynamically modifying the list of optional languages ​​in the system settings:
The content of res/xml/locales_config.xml in our demo App named multilingual settings is as follows:

<?xml version="1.0" encoding="utf-8"?>
<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
    <locale android:name="en"/>
    <locale android:name="en-GB"/>
    <locale android:name="fr"/>
    <locale android:name="ja"/>
    <locale android:name="zh-Hans-MO"/>
    <locale android:name="zh-Hant-MO"/>
</locale-config>复制

Then add under application in manifest.xml:

android:localeConfig="@xml/locales_config"
复制

Open Settings > System > Language and Input Method > Application Language > multilingual settings, you can see the list of optional languages ​​we wrote in locals_config.xml:

If we call the new setOverrideLocaleConfig method on U through the button in the App:
MainActivity#overrideLocalConfig:

public void overrideLocalConfig(View view) {
    this.getSystemService(LocaleManager.class).setOverrideLocaleConfig(new LocaleConfig(new LocaleList(Locale.ENGLISH, Locale.GERMAN, Locale.KOREAN, Locale.ITALIAN)));
}复制

After pressing the button, we returned to Settings > System > Language & Input > App Language > multilingual settings and found:

The list of optional languages ​​in the system settings becomes the language represented by the parameter we setOverrideLocaleConfig.
On T, we do not have the overrideLocalConfig API. The optional language list of the App in the system settings can only be specified by res/xml/locales_config.xml, and it cannot be changed once the App is compiled. overrideLocalConfig gives us the ability to change dynamically.

3. App language visibility of input method (IME): IME can use the getApplicationLocales() method to check the language of the current App and match the IME language to that language.

2.2 Grammatical gender change API

3 billion people speak gendered languages: languages ​​in which grammatical categories (such as nouns, verbs, adjectives, and prepositions) change depending on the gender of the person and person being spoken to or about. Traditionally, many gendered languages ​​use the masculine grammatical gender as the default or universal gender.
Addressing users with the wrong grammatical gender, such as calling a woman with the masculine gender, can have a negative impact on their performance and attitudes. In contrast, UIs with language that correctly reflects the user's grammatical gender can increase user engagement and provide a more personalized and natural user experience.
To help developers build user-centered UIs for gendered languages, Android 14 introduces the grammatical gender morphing API, which allows you to add support for grammatical gender without having to refactor your app.
The call of this feature is relatively simple. First, in Android Studio, create a new folder named values-fr-feminine under the res folder, create strings.xml in it, and only include the Text with grammatical gender is included. In this example, French text without grammatical gender should be placed in res/values-fr/strings.xml. The official documentation is available for adding translations for languages ​​with grammatical gender.
We can then set the grammatical gender for the app:


this.getSystemService(GrammaticalInflectionManager.class).setRequestedApplicationGrammaticalGender(Configuration.GRAMMATICAL_GENDER_FEMININE);复制

The above code sets the grammatical gender of the app to feminine, which assumes the user is female.
To get the grammatical gender int value of the App, you can:


int gender = this.getSystemService(GrammaticalInflectionManager.class).getApplicationGrammaticalGender();复制

There are 4 int values ​​related to grammatical gender on Android 14, which are:


Configuration.GRAMMATICAL_GENDER_NOT_SPECIFIED, Configuration.GRAMMATICAL_GENDER_NEUTRAL, Configuration.GRAMMATICAL_GENDER_FEMININE, Configuration.GRAMMATICAL_GENDER_MASCULINE复制

2.3 Regional preference

Regional preferences enable users to personalize temperature units, first day of week and numbering system. Europeans living in the US may prefer temperature units in Celsius rather than Fahrenheit, and want apps to treat Monday as the start of the week rather than the US default of Sunday.
Android 14 provides users with a centralized place to change these app preferences. These preferences also persist during backup and restore processes. Several APIs and intents (such as getTemperatureUnit and getFirstDayOfWeek) grant an app permission to read the user's preferences so the app can adjust how it displays information. Developers can also register a BroadcastReceiver on ACTION_LOCALE_CHANGED to receive broadcasts when locale preferences change.
To find these settings, open Settings and navigate to System > Languages ​​& input > Regional preferences.

2.4 Customize the behavior of the sharing table and improve the ranking of direct sharing targets

Android 14 updates the system's breakdown to support custom app behavior and provide users with more useful preview information.

2.4.1 Add custom behavior

In Android 14, apps can customize their behavior in the system share sheet. In the share table, you can use ChooserAction.Builder to build a custom ChooserAction, specifying the list of ChooserActions as the Intent.EXTRA_CHOOSER_CCUSTOM_ACTIONS of the Intent created using Intent.createChooser.

The following is the general process for creating custom behaviors

以发送多张图片为例
//创建Intent
Intent shareIntent1 =new Intent();
shareIntent1.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent1.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
shareIntent1.setType("image/*");//各种类型的图像

Intent shareIntent = Intent.createChooser(shareIntent1,null);

shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

//添加自定义行为的intent
PendingIntent customAction = PendingIntent.getBroadcast(
        mContext,
        1,
        new Intent(CHOOSER_CUSTOM_ACTION_BROADCAST_ACTION),
        PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_CANCEL_CURRENT);
PendingIntent fakeCustomAction = PendingIntent.getBroadcast(
        mContext,
        1,
        new Intent("some_action"),
        PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_CANCEL_CURRENT);

PendingIntent fakeCustomAction2 = PendingIntent.getActivity(
        mContext,
        1,
        new Intent(CHOOSER_CUSTOM_ACTION_BROADCAST_ACTION),
        PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_CANCEL_CURRENT);
//创建action
ChooserAction[] actions = new ChooserAction[] {
        createChooserAction("act1", fakeCustomAction2),
        createChooserAction("act2", fakeCustomAction),
        createChooserAction("act3", fakeCustomAction),
        createChooserAction("act4", fakeCustomAction),
        createChooserAction("act5", customAction),
};
PendingIntent modifyShare = PendingIntent.getBroadcast(
        mContext,
        1,
        new Intent(CHOOSER_CUSTOM_ACTION_BROADCAST_ACTION),
        PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_CANCEL_CURRENT);
//创建修改分享媒体资源的action
ChooserAction modifyShareAction = new ChooserAction.Builder(
        Icon.createWithResource(
                mContext.getPackageName(),
                R.drawable.img),
        modifyShareLabel,
        modifyShare
).build();
//将自定义行为存到intent里
shareIntent.putExtra(Intent.EXTRA_CHOOSER_MODIFY_SHARE_ACTION, modifyShareAction);
mContext.startActivity(shareIntent);复制
2.4.2 Improve ranking of directly shared goals

In order to provide users with more useful results, Android 14 uses more tags from the app to determine the ranking of directly shared objects. To provide more useful labels, shortcut usage is reported by calling pushDynamicShortcut with the corresponding shortcut when a user sends a message to a contact. And attach the corresponding capability "actions.intent.SEND.MESSAGE" to the shortcut by calling ShortcutInfoCompat.Builder#addCapabilityBinding("actions.intent.SEND_MESSAGE").

The following methods can help improve the ranking of directly shared goals

  1. Ensure that all shortcutIds are unique and not reused on different targets.
  2. Ensure the shortcut is long-lived by calling setLongLived(true).
  3. Provide ranking directly and set it with setRank()
  4. For social applications
  • Provide a set key for the relevant Person object in the shortcut
  • Shortcuts connect to related notifications from the same person or multiple people
  • In the provided Person object, provide a valid URI for the associated contact on the device

2.5 Support internal application animation and custom animation

Android 13 introduces predictive return animations in developer options. When supported app usage is turned on in Developer Options, swiping back displays an animation indicating the back gesture to exit the app and return to the home screen.

Android 14 has made many improvements to predictive return and added many new features:

In the newly released preview version of Android 14, the predictive return of all functions remains in the developer options. Please refer to the Developer Guide tosupport your app's predictive return gesture, and also use the Developer Guide tocreate your own Define application internal transition animation.

2.6 Improvements to the App Store

Android 14 introduces several new PackageInstaller APIs to improve the app store user experience.

2.6.1 Ask for user consent before downloading

Generally, user consent is required to install or update an app. When the installer uses the REQUEST_INSTALL_PACKAGES permission to try to install a new application, in versions prior to Android 14, the application can apply for permissions from the user after the APKs are written into the session and the session has been submitted.
Starting from Android 14, the requestUserPreapproval() method allows the installer to apply for user consent before submitting the session. This improvement allows app stores to obtain user consent before downloading APKs. And once the user agrees to the installation, the app store can download and install it in the background, which will not interfere with the user's normal use and help improve the user experience.

2.6.2 Responsible for future updates

The installer uses the new method setRequestUpdateOwnership() to indicate to the system that it is responsible for future updates of the applications it installs. This feature enforces update ownership, meaning only the update owner can install automatic updates for an app. Enforcing update owner identification helps ensure that users only receive updates from the intended app store.
Any other installer, including those using the INSTALL_PACKAGES permission, must explicitly receive the user's consent to install updates. If the user decides to update the app from somewhere else, the installer who owns the update will lose ownership of the update.

2.6.3 Update applications with as little interruption as possible

App stores should avoid updating apps that users are using because updating may kill the app that is being used and interrupt what the user is doing.
Starting with Android 14, the IntallConstraints API provides users with a way to ensure that applications are updated at an appropriate time. For example, an app store can ensure that the user is no longer interacting with the app when an update is submitted by calling the commitSessionAfterInstallConstraintsAreMet() method.

2.6.4 Seamlessly install split APKs

By splitting, an entire APK can be split into several scattered APK files according to functions. Splitting APKs allows app stores to optimize the release of different components of the app. For example, an app store might optimize based on the characteristics of the target hardware. Since API 22, the PackageInstaller API supports split APK operations.
In Android 14, the installer uses the setDontKillApp() method to declare that when installing a new part of the split APK, the process of the running application should not be killed. App stores can use this feature to seamlessly install new parts of an app while the user is using it.

2.7 Monitor user screenshot behavior

To create a standardized screenshot detection experience, Android 14 introduces a privacy-preserving screenshot detection API. This API allows applications to register callbacks on a per-activity basis. When the Activity takes a screenshot while visible, the Activity will call these callbacks and notify the user of some information.

API usage process

  • Declare the "android.permission.DETECT_SCREEN_CAPTURE" permission

<uses-permission android:name="android.permission.DETECT_SCREEN_CAPTURE" />复制
  • Implement a callback interface and rewrite the onScreenCapture() function.

final Activity.ScreenCaptureCallback screenCaptureCallback =
    new Activity.ScreenCaptureCallback() {
        @Override
        public void onScreenCaptured() {
            // Add logic to take action in your app.
        }
    };复制
  • Registration: Register screenCaptureCallback() in the Activity's onStart() method

@Override
protected void onStart() {
    super.onStart();
    // Pass in the callback created in the previous step
    // and the intended callback executor (e.g. Activity's mainExecutor).
    registerScreenCaptureCallback(executor, screenCaptureCallback);
}复制
  • Unregister: Unregister screenCaptureCallback in the activity's onStop() method

@Override
protected void onStop() {
    super.onStop();
    unregisterScreenCaptureCallback(screenCaptureCallback);
}复制

Note: The conditions for triggering callback function execution by taking screenshots:

  1. Effective: It will only be triggered when the user performs a specific key combination, such as power key + volume key down
  2. Does not take effect: The callback function will not be called for screenshots taken through adb or during instrumentation testing that captures the device's current screen content.

2.8 Paths are queryable and interpolable

Android's Path API is a powerful and flexible mechanism for creating and rendering vector graphics, capable of drawing or filling paths, and by constructing line segments or quadratic or cubic curve paths, and then performing corresponding operations. to get more complex shapes. The internal information of the path object is opaque to the caller.
Create a path and add path fragments through methods such as moveTo(), lineTo() and cubicTo(). However, every piece of content inside the entire road is not accessible, so you must save relevant information at the beginning of creating the path.

Starting from Android 14, you can query the content of each path. The path contents are stored in the PathIterator object, which can be obtained through the Path.getPathIterator method.

2.8.1 Query path segment content

Path path = new Path();
path.moveTo(1.0F, 1.0F);
path.lineTo(2.0F, 2.0F);
path.close();
PathIterator pathIterator = path.getPathIterator();复制

Through the above code, you can get the PathIterator object, which contains the information of the path fragment. The path information of the PathIterator object can be accessed through the PathIterator iterator.

while (pathIterator.hasNext()) {
    PathIterator.Segment segment = pathIterator.next();
    Log.i(LOG_TAG, "segment: " + segment.getVerb() + ", " + segment.getPoints());
}复制
2.8.2 Path interpolation

Query paths can be used to interpolate paths. That is, through two paths with the same internal structure, a new path is generated through the interpolate() interpolation method. Construct two paths, path and path2, and use the interpolation method interpolate() to obtain the resultPath. The resultPath is obtained by linear interpolation of path and path2, and the interpolation factor is 0.8f. The three paths are shown below.

Path path = new Path();
path.lineTo(300, 1200);
Path path2 = new Path();
path2.moveTo(300f,600f);
path2.lineTo(600, 1200);
Path resultPath = new Path();
if(path.isInterpolatable(path2)){
    path.interpolate( path2, 0.8f, resultPath);
}复制

Note: To be able to interpolate two paths, the internal structures of the two paths need to be the same. That is, the number of midpoints in the path is the same; the method of constructing the corresponding path segments is the same, for example, they are all constructed using the lineTo() method; and the weight of the curve is the same (the current method of using weight is conicTo(float x1, float y1, float x2, float y2 , float weight)).

2.9 OpenJDK 17 Update

  • Approximately 300 java.base classes updated to support Java 17.
  • Text Blocks, bringing multiline string literals to Java.
  • Pattern matching for instanceof, which allows an object to be treated as having a specific type from instanceof without any other variables.
  • Sealed classes allow restrictions on which classes and interfaces can extend or implement them.

3. Behavior changes that affect applications

3.1 Behavior changes: all apps

3.1.1 The permission to set precise alarm clock is turned off by default

Precision alarms are suitable for user-intended notifications or actions that need to occur at precise times.
SCHEDULE_EXACT_ALARM is a permission introduced in Android 12 that allows apps to schedule accurate alarms. This permission is no longer pre-granted for most newly installed apps with targetSDK>= Android 14 (set to deny by default). If the user transfers app data to a device running Android 14 through a backup restore operation, permission will still be denied. If an existing app already has this permission, it will be pre-granted when the device is upgraded to Android 14.
The SCHEDULE_EXACT_ALARM permission is required to initiate accurate alerts via the following API, otherwise a SecurityException will be thrown:

  • setExact()
  • setExactAndAllowWhileIdle()
  • setAlarmClock()

Existing best practices for the SCHEDULE_EXACT_ALARM permission still apply, including the following:

  • Use canScheduleExactAlarms() to check permissions before scheduling the exact alarm.
  • Set up the app to listen and react appropriately to the foreground broadcast AlarmManager.ACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED, which is sent when the user grants permission.

On U, even if the App is declared in AndroidManifest.xml


<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />复制

The system will not automatically grant the android.permission.SCHEDULE_EXACT_ALARM permission after installation. If the App does not have this permission, the system will throw SecurityException when calling the three methods of AlarmManager#setExact, AlarmManager#setAlarmClock and AlarmManager#setExactAndAllowWhileIdle to set precise alarms.
If the App wants to obtain this permission, the user needs to open it manually in the application information or Settings->Apps->Special app access->Alarms & reminders:

3.1.1.1 Affected applications

If the device is running Android 14 or higher, this change will affect newly installed apps with the following characteristics:

  • targetSDK >= Android 13 。
  • Declare the SCHEDULE_EXACT_ALARM permission in AndroidManifest.xml.
  • Not an exemption or pre-authorization situation.
  • Not a calendar or alarm clock app.
3.1.1.2 Calendar and alarm clock applications should declare the USE_EXACT_ALARM permission

Calendar or alarm clock apps need to send calendar reminders, wake alerts, or alerts when the app is no longer running. These apps can request the USE_EXACT_ALARM normal permission. The USE_EXACT_ALARM permission will be granted at installation time, and an application with this permission will be able to schedule the exact alarms as an application with the SCHEDULE_EXACT_ALARM permission. Xiaomi App Store will strengthen the control of this permission.

3.1.1.3 Usage scenarios where a precise alarm clock may not be needed

Since the SCHEDULE_EXACT_ALARM permission is now denied by default and the permission grant process requires additional steps from the user, developers are strongly encouraged to evaluate their use cases and determine whether the exact alert still makes sense for their use case.
The following list shows common workflows that may not require exact alerts:

  • Schedule recurring work over the life of the application

The set() method is useful if the task needs to keep real-time constraints in mind, such as starting tomorrow at 2:00 PM or in 30 minutes. Otherwise, it is recommended to use the postAtTime() or postDelayed() methods instead.

  • Scheduled background work, such as updating your application and uploading logs

WorkManager provides a way to schedule time-sensitive periodic work. You can provide a repeat interval and a flexInterval (at least 15 minutes) to define the fine-grained run time of the job.

  • When the system is idle, an alarm needs to be raised at approximately a certain time

Use inaccurate alerts. Specifically, call setAndAllowWhileIdle().

  • A user-specified action that should occur after a specific time

Use inaccurate alerts. Specifically, call set().

  • User-specified actions that can occur within a time window

Use inaccurate alerts. Specifically, call setWindow(). Note that the minimum allowed window length is 10 minutes.

3.1.1.4 Migration steps to continue using Accurate Alarm Clock

Applications must check whether they have permission before scheduling the exact alert. If apps don't have permission, they must request permission from the user by calling an intent.
This is the same standard workflow for requesting special permissions:

  1. The application should call AlarmManager.canScheduleExactAlarms() to confirm that it has the appropriate permissions.
  2. If the application does not have permission, call an intent containing ACTION_REQUEST_SCHEDULE_EXACT_ALARM along with the application package name to request the user to grant permission. Check the user's decision in your app's onResume() method.
  3. Listen for the AlarmManager.ACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED broadcast sent when the user grants permission.
  4. Your app can set exact alerts if the user grants your app permission. Instead, if the user denies the permission, gracefully degrade your app experience so that it provides functionality to the user without the information protected by the permission.

Best practice: Use alarmManager.canScheduleExactAlarms() to first check whether there is SCHEDULE_EXACT_ALARM permission. If not, use startActivity to apply for permission from the user:

boolean canScheduleExactAlarms = mAlarmManager.canScheduleExactAlarms();
if(!canScheduleExactAlarms) {
    Intent permissionIntent = new Intent();
    permissionIntent.setAction("android.settings.REQUEST_SCHEDULE_EXACT_ALARM");
    startActivity(permissionIntent);
}
复制
3.1.1.5 Degrade appropriately when permission is denied

Some users will deny permission. In this case, we recommend that the application gracefully degrades the experience and still strives to provide the best fallback user experience by identifying its use case.

3.1.1.6 Exceptions

The following types of apps are always allowed to call the setExact() or setExactAndAllowWhileIdle() method:

  • Applications signed with platform certificates.
  • Privileged applications.
  • Apps on the power permission list (if your app meets the requirements, you can use the ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS intent to request the action).
3.1.1.7 Pre-authorization

Role holders of SYSTEM_WELLBEING will be pre-granted SCHEDULE_EXACT_ALARM.

3.1.1.8 Testing guidance

To test this change, disable your app's Alarms and Reminders permission from the Special App Access page in System Settings (Settings > Apps > Special App Access > Alarms & Reminders) and observe your app's behavior.

3.1.2 When the application is in cached state, dynamically registered broadcasts will be queued

In Android 14, when the application is in the cache state, the system can put the context-registered broadcast into the queue. This is similar to the queuing behavior introduced in Android 12 (API level 31) for asynchronous binder transactions. Broadcasts declared in the Manifest.xml file are not queued and the application is removed from cached state to send the broadcast.
When the application leaves the cached state, such as when it returns to the foreground, the system will distribute the queued broadcast. And multiple instances of some broadcasts are combined into one. Depending on other conditions, such as system health, the application is removed from the cached state and previously queued broadcasts are delivered.

3.1.3 Third-party apps can only kill their own background processes

Starting from Android 14, when the App calls killBackgroundProcesses(), this API can only kill its own background process.
If the package name of another App is passed in, this method has no impact on the background process of the App, and the following information will appear in Logcat:


Invalid packageName: com.example.anotherapp复制

Apps should not use the killBackgroundProcesses() API or otherwise attempt to affect the process lifecycle of other apps, even on older Android versions. Android is designed to keep cached apps in the background and automatically terminate them when the system needs memory. If an app kills other apps unnecessarily, it slows down system performance and increases battery consumption because those apps later need to be fully restarted, which takes up far more resources than restoring an existing cached app.

3.1.4 Minimum targetSdk API level required to install the application

Starting from Android 14, apps with targetSdkVersion lower than 23 cannot be installed. Requiring apps to meet these minimum target API levels can improve user security and privacy.

Malware often targets older levels of APIs, bypassing security and privacy protections introduced in newer Android versions. For example, some malicious apps use targetSdkVersion 22 to avoid being affected by the runtime permissions model introduced in 2015 with Android 6.0 Marshmallow (API level 23). This change in Android 14 makes it difficult for malware to avoid security and privacy improvements. Applications with lower API levels will fail to install with the following message in the log:

INSTALL_FAILED_DEPRECATED_SDK_VERSION: App package must target at least SDK version 23, but found 7复制

On devices upgraded to Android 14, any app with a targetSdkVersion lower than 23 will remain installed.

If you need to test your application against the old API level, use the following adb command:

adb install --bypass-low-target-sdk-block FILENAME.apk复制
3.1.5 Hide the application package name where the media is located

Media storage supports querying the OWNER_PACKAGE_NAME column, which represents the application package name where media files are stored. Starting from Android 14, one of the following two conditions must be met before the value of this column can be queried.

  • The package name of an application that stores media files is visible to other applications

If you want a certain program package name to be visible to other applications, then other applications must add <queries> in the Manifest.xml file. The package name of the package is the package name of the other application that you want to apply for.

For example, if testmediastore wants to query the information of testmediastore2, then the package name of <queries> in the Mainfest.xml file is the package name of testmediastore2.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.mimi.testmediastore">
    //.../
    <queries>
        <package android:name="com.mimi.testmediastore2"/>
    </queries>
    //../
</manifest>复制
  • Applications that query media storage apply for QUERY_ALL_PACKAGE permission.
3.1.6 Changes to resident notifications

If an app displays persistent notifications to the user, Android 14 allows the user to turn off such notifications.
This change applies to apps that prevent the user from manually deleting foreground notifications by setting Notification.FLAG_ONGOING_EVENT via Notification.Builder#setOngoing(true) or NotificationCompat.Builder#setOngoing(true). The behavior of FLAG_ONGOING_EVENT has been changed so that such notifications can actually be removed manually by the user.

Such notifications remain unclosable under the following circumstances:

  • When the phone is locked
  • If the user chooses to clear all notification actions (this helps prevent accidental dismissals)
  • Additionally, this new behavior does not apply to non-closable notifications in the following use cases:
  • Notifications bound to real calls using CallStyle
  • Notifications created using MediaStyle
  • Device Policy Controller (DPC) and Enterprise Support Packages

3.1.7 Grant access to some photos or videos

When an app on Android 14 requests the READ_MEDIA_IMAGES or READ_MEDIA_VIDEO permissions introduced in Android 13 (API level 33), it can optionally grant partial access.
Note: TargetSDK≥33, applications on Android 14 will be affected by this change.

3.1.7.1 New pop-up window display content

Before Android 14:

To access media images or videos, you need to apply for permissions READ_MEDIA_IMAGES and READ_MEDIA_VIDEO. When an application applies for any of the above two permissions, the pop-up permission box only has the following two options. That is, allow (allow means allow all photos) and disallow.

Android 14:

When applying for permissions READ_MEDIA_IMAGES and READ_MEDIA_VIDEO to access media files, there are three options in the pop-up box. Select photos and videos: Select some pictures to allow apps to access
Allow all: Allow access to all images
Don't allow: Deny access to all images

If the user selects "SELECT PHOTOS AND VIDEOS" and later the app requests READ_MEDIA_IMAGES or READ_MEDID_VIDEO again, a different dialog will be displayed giving the user the opportunity to grant full access, keep the current selection, or grant additional photos and videos. After a while, the system will display the system selector directly.

To help applications support the new changes, a new permission READ_MEDIA_VISUAL_USER_SELECTED has been introduced. The system behaves differently depending on whether your application uses the new permissions.

Note: If your application already uses a photo picker, you don't need to take any action to support this change. Otherwise, consider using the photo picker instead of adopting this change.

3.1.7.2 If the application is not adapted

If the READ_MEDIA_VISUAL_USER_SELECTED permission is not declared, the following behavior occurs: the READ_MEDIA_IMAGES and READ_MEDI_AVIDEO permissions are granted during the app session and provide temporary permission grants and temporary access to user-selected photos and videos. When the user actively kills the app, the system will eventually deny these permissions. This behavior is the same as other one-time permissions.
If the app wants to access additional photos and videos in the future, it must manually request the READ_MEDIA_IMAGES or READ_MEDIA_VIDEO permission again. The system follows the same process as the initial permission request, prompting the user to select photos and videos.

This change will not affect apps if they follow best practices. This is true if the app does not retain URI access, store system permission state, or refresh the displayed image set after permission changes. However, depending on the application, performance may not be ideal.
Note: Your app does not need any media permissions to use the photo picker or any system intent, such as ACTION_GET_CONTENT or ACTION_OPEN_DOCUMENT.

3.1.7.3 Migrations to control behavior in applications

If the READ_MEDIA_VISUAL_USER_SELECTED permission is declared and the user selects "SELECT PHOTOS AND VIDEOS" in the system pop-up box, the following situation will occur: both the READ_MEDIA_IMAGES and READ_MEDIA_VIDEO permissions will be denied.
Grant the application READ_MEDIA_VISUAL_USER_SELECTED permission to temporarily access photos and videos that the user has selected.
If you want to apply for other photos or videos, you must apply for READ_MEDIA_IMAGES or READ_MEDIA_VIDEO permission again.

Note: Create a UI interface in the application that users must press before reapplying for READ_MEDIA_IMAGES or READ_MEDIA_VIDEO permissions. Prevent users from being surprised when they see the system pop-up box again.

READ_MEDIA_IMAGES and READ_MEDI_AVIDEO are the only other permissions users use to access their photo and video media libraries. Declaring READ_MEDIA_VISUAL_USER_SELECTED makes the permission controller aware that your app supports manual re-requests for selecting more photos and videos.

To prevent users from seeing multiple system permission request pop-ups, request permissions for READ_MEDIA_VISUAL_USER_SELECTED, ACCESS_MEDIA_LOCATION and access media (READ_MEDIA_IMAGES or READ_MEDIA_VIDEO or both) in one operation.

3.1.7.4 Retain access to photos and videos when device is upgraded

If the device on which the app is located is upgraded from a previous Android version to Android 14, the system will maintain full access to the user's photos and videos and automatically grant the app some permissions. The final permissions granted depend on the permissions the app had before the device was upgraded to Android 14.

  • Upgrading from Android 13
  1. App installed on Android 13.
  2. The application has READ_MEDIA_IMAGES and READ_MEDIA_VIDEO permissions.
  3. When the device is upgraded to Android 14, the app is still installed.

If the above three conditions are met, the app still has permission to access all photos and videos. The system will automatically grant the application READ_MEDIA_IMAGES and READ_MEDIA_VIDEO permissions.

  • Upgrading to Android 14 from Android 12 or earlier
  1. App installed on Android 12 or earlier.
  2. The application has READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permission.
  3. When the device is upgraded to Android 14, the app is still installed.

If the above three conditions are met, the app still has permission to access all photos and videos. The system will automatically grant the application READ_MEDIA_IMAGES and READ_MEDIA_VIDEO permissions.

3.1.7.5 Best solution

Here are the best options for using the READ_MEDIA_VISUAL_USER_SELECTED permission.

  • Background media requires new permissions

When the application performs media processing, compressing or uploading media files in the background, the READ_MEDIA_IMAGES and READ_MEDIA_VIDEO permissions are in a denied state. It is highly recommended to add support for READ_MEDIA_VISUAL_USER_SELECTED. Or the app should query whether a specific photo or video can be accessed by using an InputStream or using a ContentResolver.

  • Do not store permission status

Do not store permission status permanently via SharedPreferences or DataStore. The stored permission status may be out of sync with the actual status. Permission status can change upon a permission reset, app hibernation, user-initiated app settings change, or when the app goes into the background. Instead, use ContextCompat.checkSelfPermission() to check storage permissions.

  • Sometimes not all photos or videos are fully accessible

Based on the changes introduced in Android 14, apps may only be able to access some of the contents of the photo library. When an application query uses ContentResolver to query cached media data, the cached data may not be the latest.

The following method can be used to solve the problem: do not rely on the storage cache, but use ContentResolver to directly query the media library
When the application is in the foreground, save the results to the storage.

  • URI is temporary access

If the user selects "SELECT PHOTOS AND VIDEOS" in the system permissions dialog box, the access time to the selected photos and videos is limited. The application should be able to handle the situation of not being able to access any Uri, regardless of whether the application has permissions or not.

3.1.8 Non-linear scaling to 200%

Starting from Android 14, the system supports 200% font scaling, providing additional accessibility options for low-vision users that comply with the Web Content Accessibility Guidelines (WCAG).
To prevent large text elements from scaling too much on the screen, the system applies a non-linear scaling curve. This scaling strategy means that large text is scaled at a different rate than small text. Nonlinear font scaling helps maintain a hierarchy of proportions between elements of different sizes while mitigating highly linear text scaling issues (such as text being clipped or becoming difficult to read due to the display size being too large).

3.1.8.1 Testing applications using non-linear scaling

If you use scaled pixel (sp) units to define text size, these additional options and scaling improvements will automatically be applied to the applied text. However, UI testing should be performed with the maximum font size enabled (200%) to ensure that the app uses font sizes correctly and can accommodate larger fonts without affecting usability.

To enable 200% font size, perform the following steps:

  • Open settings and go to "Accessibility" > "Show text and size".
  • Find the font size option and press the + button to know the maximum zoom size
3.1.8.2 Use scaled pixel (sp) as the text size unit

Remember to always specify text size in sp units. When an application uses sp units, Android can apply the user's preferred text size and scale appropriately.
Do not use sp as the distance or height unit between views. For non-linear scaling in sp units, the zoom size will be disproportionate. For example, 4sp+20sp does not equal 24sp.
3.1.8.3 Convert scaled pixel (sp) units
Use the TypedValue.applyDimension() method to convert the sp unit to pixels unit, and use TypedValue.deriveDimension() Method to convert pixels unit to sp unit. These methods automatically apply appropriate nonlinear scaling curves.
Avoid using Configuration.fontScale or DisplayMetrics.scaledDensity. Because font scaling is now non-linear, these values ​​will no longer be accurate.

3.2 Behavior changes: Apps targeting Android 14

3.2.1 The front-end service type must be declared

To help developers more intentionally define user-facing foreground services, Android 10 introduces the android:foregroundServiceType attribute.
If the App targets Android 14, it must specify the appropriate frontend service type. As in previous Android versions, multiple types can be combined. The available front-end service types are: camera, connectedDevice, dataSync, health, location, mediaPlayback, mediaProjection, microphone, phoneCall, remoteMessaging, shortService, specialUse, systemExempted.
If the usage scenario in the app is not related to any of these types, we strongly recommend using WorkManager or user-initiated data transfer jobs.
The new front-end service types in Android 14 are health, remoteMessaging, shortService, specialUse and systemExempted types.
The following code snippet provides an example of a front-end service type declaration in AndroidManifest.xml:


<manifest ...>
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
    <application ...>
      <service
          android:name=".MyMediaPlaybackService"
          android:foregroundServiceType="mediaPlayback"
          android:exported="false">
      </service>
    </application>
</manifest>复制

If an app targeting Android 14 does not define the type of a given service in AndroidManifest.xml, the system will throw a MissingForegroundServiceTypeException when calling startForeground() for the service.

3.2.1.1 Declare new permissions using front-end service types

If apps targeting Android 14 use foreground services, they must declare the specific permissions introduced by Android 14 based on the foreground service type. All permissions are defined as normal permissions and granted by default. Users cannot revoke these permissions. If startForeground() is called without declaring the appropriate permissions for the foreground service type, a SecurityException will be thrown.

3.2.1.2 Including foreground service types at runtime

The best practice for applications that start a foreground service is to use an overloaded method of startForeground(), where you can pass in a bitwise integer of the foreground service type. You can optionally pass one or more type values.
In general, you should declare only the types required for a specific use case. This makes it easier to meet system expectations for each front-end service type. If the foreground service is started as multiple types, the foreground service must comply with the platform implementation requirements for all types.
However, if you start a foreground service that uses any of the following types, these types should always be included each time startForeground() is called for that service:
FOREGROUND_SERVICE_TYPE_CAMERA, FOREGROUND_SERVICE_TYPE_LOCATION, FOREGROUND_SERVICE_TYPE_MICROPHONE.
If the foreground service type is not specified in the call, it will default to the value defined in AndroidManifest.xml.
Simply put, the new feature requires developers to declare the front-end service type and required permissions in the manifest when using the front-end service:


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
    <application
    ...
        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"
            android:foregroundServiceType="mediaPlayback" />复制

You can also declare types when starting the foreground service, but the types declared here should be a subset of the types in the manifest, and the final foreground service type follows the declaration in startForeground.
MyService#onStartCommand:


startForeground(222, notification, FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK);复制

This starts a foreground service.

3.2.1.3 System runtime check

The system checks that the foreground service type is used correctly and that the app has requested the correct runtime permissions or used the required APIs. For example, the system expects applications using the foreground service type FOREGROUND_SERVICE_TYPE_LOCATION to request ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION.
This means that the app must follow a very specific sequence of operations when requesting permissions from the user and starting foreground services. Permission must be requested and granted before the app attempts to call startForeground(). Apps that request appropriate permissions after the foreground service starts must change this order of operations and request permissions before starting the foreground service.
Note: If your app does not meet all runtime requirements to start a foreground service, the system throws a SecurityException after calling startForeground() for the service. This prevents the foreground service from starting, may cause the running foreground service to be removed from the foreground process state, and may cause the app to crash.

3.2.1.4 Expected usage scenarios and corresponding service type checks

In order to use a given front service type, specific permissions must be declared in the manifest file, specific runtime requirements must be met, and the app must meet a set of expected usage scenarios for that type. The following sections explain the permissions that must be declared, the runtime requirements, and the intended usage scenarios for each type.

3.2.2 OpenJDK 17 update

Changes to regular expressions: Invalid group references are now disallowed to more closely follow OpenJDK's semantics. You may see new cases where the java.util.regex.Matcher class throws an IllegalArgumentException, so be sure to test areas of your app where regular expressions are used. To enable or disable this change when testing, use the Compatibility Framework tool to toggle the DISALLOW_INVALID_GROUP_REFERENCE flag.
UUID handling: The java.util.UUID.fromString() method now performs stricter checks when validating input parameters, so an IllegalArgumentException may occur during deserialization. To enable or disable this change when testing, use the Compatibility Framework tool to toggle the ENABLE_STRICT_VALIDATION flag.
ProGuard issue: In some cases, adding the java.lang.ClassValue class can cause problems when trying to minify, obfuscate, and optimize your app using ProGuard. The issue stems from a Kotlin library that changes runtime behavior depending on whether Class.forName("java.lang.ClassValue") returns a class. If the app is developed against an older version of the runtime where the java.lang.ClassValue class is not available, these optimizations may remove the computeValue method from classes that inherit from java.lang.ClassValue.

3.2.3 Restrictions on implicit intentions and pending intentions

For apps targeting Android 14, Android restricts apps from sending implicit intents to internal components in the following ways:

  • Implicit intents are only sent to exported components. Applications must use display intents sent to unexported components or mark components as exported.
  • If an application creates a mutable pending intent that does not specify a component or package name, the system throws an exception.

These changes prevent malicious applications from intercepting implicit intent used by components inside the application.

For example, here is the intent filter declared in the manifest file:

<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>复制

If the application attempts to use an implicit intent to launch this activity, an exception will be thrown:

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

In order to launch an activity without an export, the app must use a display intent:

// This makes the intent explicit.
Intent explicitIntent =
        new Intent("com.example.action.APP_ACTION")
explicitIntent.setPackage(context.getPackageName());
context.startActivity(explicitIntent);复制
3.2.4 Dynamically registered broadcast receivers must declare the export flag

For the Android 14 platform, apps or services on which a receiver is registered using a context need to declare a flag indicating whether the receiver is exported to other apps or devices. The flag is RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED. This requirement helps protect apps from security vulnerabilities by leveraging features introduced in Android 13 regarding receivers.

For example, a context-registered broadcast receiver declares RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED:

// This broadcast receiver should be able to receive broadcasts from other apps.
// This option causes the same behavior as setting the broadcast receiver's
// "exported" attribute to true in your app's manifest.
context.registerReceiver(sharedBroadcastReceiver, intentFilter,
    RECEIVER_EXPORTED);

// For app safety reasons, this private broadcast receiver should **NOT**
// be able to receive broadcasts from other apps.
context.registerReceiver(privateBroadcastReceiver, intentFilter,
    RECEIVER_NOT_EXPORTED);复制

If the application uses the Context#registerReceiver method to register a receiver only for system broadcasts, then the application does not need to declare the above flag.

3.2.5 Safer dynamic code loading

If your app targets Android 14 and uses dynamic code loading (DCL), all dynamically loaded files must be marked read-only. Otherwise, the system will throw an exception. We recommend that apps avoid dynamically loading code whenever possible, as doing so greatly increases the risk of the app being compromised through code injection or code tampering.
If code must be loaded dynamically, use the following method to make dynamically loaded files (such as DEX, JAR, or APK files) read-only immediately after the file is opened and before anything is written: < /span>

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

Handling existing dynamically loaded files
To prevent existing dynamically loaded files from throwing exceptions, we recommend deleting and recreating them before trying to dynamically load them again in your application . When recreating the file, follow the previous guidance to mark the file as read-only while writing. Alternatively, existing files can be remarked as read-only, but in this case we strongly recommend verifying the integrity of the file first (for example, by checking the file's signature against a trusted value) to help protect the app from malicious operate.

3.2.6 Preventing zip file path penetration attacks

For apps targeting Android 14, Android protects against Zip path penetration vulnerabilities by: If the zip file entry name contains ".." or starts with "/", ZipFile(String) and ZipInputStream.getNextEntry( ) will throw ZipException.
Applications can choose to turn off this validation by calling dalvik.system.ZipPathValidator.clearCallback().

3.2.7 Additional restrictions on starting Activity in the background

For applications whose target platform is Android 14, the system further restricts the application's permission to start activities in the background. The purpose is to protect users by preventing malicious programs from abusing the API to launch destructive activities from the background.

3.2.7.1 When the system allows background applications to start Activity

The new restrictions in Android 14 mainly limit these situations.

Exceptions to the restrictions on starting activities in the background are mainly:

  • An application has a visible window, such as a foreground Activity.
  • The application owns the Activity in the back stack of the foreground task.
  • The application owns the Activity in the back stack of an existing task on the Recents screen.
  • An Activity of the application was started not long ago
  • The application recently called finish() for an Activity. This only applies if the app has an Activity in the foreground or on the back stack of a foreground task when finish() is called.
  • Apps have system-bound services. This only applies to the following services, which may require a startup interface: AccessibilityService, AutofillService, CallRedirectionService, HostApduService, InCallService, TileService, VoiceInteractionService, and VrListenerService.
  • A service in an application is constrained by another visible application. Note that the app bound to the service must remain visible for the background app to successfully launch the activity.
  • A service in an application is constrained by another visible application. Note that the app bound to the service must remain visible for the background app to successfully launch the activity.
  • The application receives a PendingIntent notification from the system. For pending Intents from services and broadcast receivers, the application can start the Activity a few seconds after the pending Intent is sent.
  • The application receives a PendingIntent from another visible application.
  • The app receives a system broadcast in which it should launch the interface. Including ACTION_NEW_OUTGOINF_CALL and SECRET_CODE_ACTION. The application can start the activity a few seconds after the broadcast is sent.
  • Applications are associated with supporting hardware devices through the CompanionDeviceManager API. This API supports the app launch API in response to user actions on the paired device.
  • The app is a device policy controller running in device owner mode. Example use cases include fully managed enterprise devices, as well as specialized devices such as digital signage and kiosks.
  • The user has granted the app SYSTEM_ALERT_WINDOW permission.
3.2.7.2 Two new restrictions in Android 14

3.2.7.2.1 New restriction one

When the background application uses the PendingIntent#()send() method to send PendingIntent, its related parameter ActivityOptions should be set to setPendingIntentBackgroundActivityStartMode(MODE_BACKGROUND_ACTIVITY_START_ALLOWED).

Instructions for use:

// A app创建pendingIntent
PendingIntent pendingIntent = PendingIntent.getActivity(this,
        0,
        notificationIntent,
        PendingIntent.FLAG_MUTABLE,
        null);
//通过将pendingIntent发送到B app
//B app收到创建的pendingcontent,然后执行send()方法发送,同时构建ActivityOptions,
//设置相应的模式
PendingIntent pendingIntent = intent.getParcelableExtra("pending");
ActivityOptions options 
        = ActivityOptions
 .makeBasic()
 .setPendingIntentBackgroundActivityStartMode(ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED)
 .setPendingIntentCreatorBackgroundActivityStartMode(ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
pendingIntent.send(context, 0, null, null, null, null, options.toBundle());  复制
3.2.7.2.2 New restriction 2

When a visible application uses the bindService() method to bind the service of another background application, if you want to grant the bound background service the application to start the Activity, you must call the bindService() method when binding the service. contains BIND_ALLOW_ACTIVITY_STARTS.

Instructions for use:

targetSdk<Android 14,前台应用绑定后台服务启动Activity需要BIND_AUTO_CREATE
    bindService(intent, coon, BIND_AUTO_CREATE);

targetSdk≥Android 14,前台应用绑定后台服务要启动Activity,需要在之前的基础上
添加BIND_ALLOW_ACTIVITY_STARTS标志。
    bindService(intent, coon, BindServiceFlags.of(BIND_ALLOW_ACTIVITY_STARTS|BIND_AUTO_CREATE));复制
3.2.8 Strengthen restrictions on non-SDK APIs

Starting with Android 9 (API level 28), the Android platform imposes restrictions on the non-SDK interfaces that apps can use. These restrictions apply whenever an app references a non-SDK interface or attempts to use reflection or JNI to obtain a handle to it. These limits are designed to help improve user experience and developer experience, reduce the risk of app crashes for users, and reduce the risk of emergency releases for developers.
If your app doesn't target Android 14, some of these changes may not have immediate impact. However, while apps can currently use some non-SDK interfaces (depending on the app's TargetSDK), using any non-SDK methods or fields always carries a high risk of breaking the app.
If you are not sure whether your application uses non-SDK interfaces, you can use the StrictMode API or veridex to test. If your app relies on non-SDK interfaces, you should start planning to migrate to an SDK alternative. Nonetheless, we are aware that some apps have valid use cases using non-SDK interfaces. If you can't find an alternative to using a non-SDK interface to implement your app's functionality, you can request a new public API from Google.

3.2.9 Tighten full-screen intent notification permissions

In Android 11 (API level 30), any app can use Notification.Builder.setFullScreenIntent to send a full-screen intent when the phone is locked. You can automatically grant this permission when your app is installed by declaring the USE_FULL_SCREEN_INTENT permission in the AndroidManifest.
Full-screen intent notifications are designed for very high-priority notifications that require the user's immediate attention, such as an incoming phone call or a user-set alarm. Starting in Android 14, apps allowed to use this permission are limited to apps that provide calls and alarms.
This permission remains enabled for apps installed on the phone until 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 the App has the permission; if not, the App can use the new intent ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT to launch the settings page where the user can grant the permission.

3.2.10 Data security information is more visible

3.2.10.1 Permissions considerations

For certain permissions, the system runtime permissions dialog now includes a clickable section that highlights your app's data sharing operations. This section of the system dialog contains information such as why your app might decide to share data with a third party and links users to where they can control access to your app's data.

3.2.10.2 System notification

If a user shares their location in an app and the app subsequently expands the use of their location sharing in one of the following ways, the user will see a system notification within 30 days:

  • App starts sharing location data with third parties.
  • Apps start sharing location data for advertising-related purposes.

When users click this notification, they will be taken to a new location data sharing update page, which shows a detailed list of apps that have made relevant changes, as well as the ease of changing permission settings for each app method. The image below shows an example of this process.
The new location data sharing update page is permanently accessible from the device's Settings > Privacy or Settings > Security & Privacy page and displays recently added location data sharing.

System notification that occurs when certain installed applications change their data sharing scope

4. Migration Guide

With each version of Android, new features and behavior changes are introduced with the goal of making Android more useful, secure, and performant. In many cases, apps will work out of the box on the new version and work exactly as expected, but in some cases, apps will need to be updated to adapt to platform changes.
The source code is released to AOSP (Android Open Source Project), and users can start using the new platform. So get your apps ready to run the way users expect and ideally take advantage of new features and APIs to get the most out of the platform.

There are two typical phases of migration, which can be carried out simultaneously:

  • Ensure app compatibility (before final Android 14 release)
  • Adapt the app for the new platform’s features and APIs (as soon as possible after the final version is released)

4.1 Ensure compatibility with Android 14

You must test the performance of existing applications on Android 14 to ensure that users have a good experience with the latest Android version. Some platform changes may affect app performance. Therefore, it is necessary to thoroughly test the application and make necessary adjustments.
You can usually adjust your app and release updates without changing the app's targetSdkVersion. Likewise, depending on how your app is built and what platform features it uses, you may not need to use new APIs or change your app's compileSdkVersion.
Before you start testing, be sure to familiarize yourself with the application behavior changes. Even if you don't change your app's targetSdkVersion, these changes will affect your app.

Perform Compatibility Testing
In most cases, testing Android 14 compatibility is similar to testing a normal app. This is also a time to review core application quality guidelines and testing best practices.
To test, install your currently released app on a device running Android 14 and complete all process and functional tests while looking for issues. To focus your testing, take a look at all the app behavior changes introduced in Android 14. These changes may impact your app and may cause it to crash.
Also make sure to check and test the use of restricted non-SDK interfaces. You should replace any restricted interfaces used by your app with public SDK or equivalent NDK interfaces. Watch for logcat warnings highlighting these access rights and use the StrictMode method detectNonSdkApiUsage() to catch them.
Finally, be sure to fully test the libraries and SDKs in your app to ensure they run as expected on Android 14 and adhere to the best practices for privacy, performance, UX, user experience, data handling, and permissions. best practices. If you encounter problems, try updating to the latest version of the SDK, or contact the SDK developer for assistance.
Once you have completed testing and updated, we recommend that you publish your compatible app immediately. This allows your users to test your app early and helps users transition to Android 14 smoothly.

4.2 Update the application’s target platform and build with the new API

Once a compatible version of your app is released, the next step is to add full support for Android 14 by updating the targetSdkVersion and taking advantage of the new Android 14 APIs and features. When you're ready, you can start making these updates.
As you plan to fully support Android 14, review the behavior changes for apps targeting Android 14. These targeted behavior changes may cause functional issues that then need to be addressed. In some cases, these changes require significant development work, so we recommend that you understand and resolve these issues as early as possible. To determine the specific behavior changes that affect your app, use the compatibility switches to test your app with the selected changes enabled.

Here are the steps to fully support Android 14.

  • Get the SDK, change the target platform and build with the new API

To test full Android 14 support, please use the latest preview version of Android Studio to download the Android 14SDK, as well as any other tools needed. Next, update the app's targetSdkVersion and compileSdkVersion, and then recompile the app. For more information, seeSDK Setup Guide.

  • Test Android 14 apps

After compiling and installing the app on a device running Android 14, start testing to ensure that the app runs properly on the Android 14 platform. Some behavior changes only apply when your app targets a new platform, so you need to review these behavior changes before you begin.

As with the basic test, work through all processes and features to find issues. Focus your testing on behavioral changes targeting Android 14. You can also follow the Core App Quality Guidelines and Testing Best Practices Check the application.

Ensure that possible use ofrestricted non-SDK interfaces is checked and tested. Watch for logcat warnings that highlight these access rights, and use the StrictMode method detectNonSdkApiUsage() to catch them programmatically.

Finally, be sure to fully test the libraries and SDKs in your app to ensure they run as expected on Android 14 and follow best practices for privacy, performance, UX, user experience, data handling, and permissions. If you encounter problems, try updating to the latest version of the SDK, or contact the SDK developer for assistance.

  • Switch the application compatibility test switch to test

Android 14 includes a compatibility switch that makes it easier to test targeted behavior changes in your apps. For debuggable applications, the toggle switch allows you to: Test targeted changes without actually changing the application's targetSdkVersion. You can toggle the switch to force specific targeted behavior changes to evaluate the impact on existing apps.
Only test specific changes. Instead of processing all targeted changes at once, you can use a toggle to disable all targeted changes except the changes you want to test.
Manage the switch through adb. You can enable and disable switchable changes in an automated testing environment using adb commands.
Debugging faster with standard change IDs. Each switchable change has a unique ID and name, which can be used to quickly debug the root cause in the log output.
The toggle can be useful when you're ready to change your app's target platform, or when you're actively developing to support Android 14. For more information, seeCompatibility Framework Changes (Android 14).



 

Guess you like

Origin blog.csdn.net/yzwfeng/article/details/135019917