Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

Time:2022-6-11

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

preface

Android 12 is the latest official version released in October 2021. However, many students said that it has not been adapted yet. To solve the problems encountered by developers during version adaptation, we establishedGitHub · AndroidPlatformWiki。 We hope to comprehensively and profoundly interpret each Android version update from the perspective of developers, so as to establish a systematic Android system adaptation manual. Specifically:

Two dimensions

According to the content relevance, we will interpret it from two dimensions:

  • Timeline based:At this stage, the official will release a new version every year. Therefore, it is necessary to interpret the new functions and behavior changes involved in this version based on an Android version. This can help the development students understand the updated content of the new version. For example, we will interpret the updated content of Android 13 and the adaptation self-examination table through a document;
  • Content line based:Generally, a system function module will become stable after multiple system version updates. Therefore, it is necessary to interpret the main capabilities of the function and the changes and differences of different versions in a function unit. This can help the development students understand the differences between different versions of this function. For example, we will interpret the system notification separately through a document.

Three levels

According to the classification of fault sensitivity, we divide the compatibility of system changes into three levels:

  • Forced adaptation ❗:All applications must be adapted, otherwise problems such as compilation failure, function unavailability or user experience damage will occur;
  • Recommended adaptation ⭐:Adaptation is not mandatory, but the adapted application will obtain better user experience or more secure privacy protection and other benefits;
  • Adapted:The application is compatible without any changes.

Two types of behavior change

System behavior changes usually fall into one of the following two categories:

  • Face the behavior change of all applications:All applications running on this system version will be affected regardless of the targetsdkversion of the application. Generally, these changes should be adapted and tested first to help users run your application on the new version of the system without damaging the user experience;
  • Behavior changes targeting a specific targetsdkversion:Only applications with targetsdkversion higher than or equal to the system version will be affected, usually changes with large impact or adaptation workload. We can understand it as an adaptation buffer left by Google for developers.

Android 12 adaptation self checklist

According to the classification of fault sensitivity, we divide the compatibility of Android 12 system changes into three levels:

  • Forced adaptation ❗:Changes that must be adapted for all applications involving this function, and problems such as compilation failure, function unavailability, or certain damage to the user experience may occur for unadapted applications;
  • Recommended adaptationThe change of adaptation is not mandatory, and the adapted application has better user experience or more secure privacy protection;
  • Adapted:Apply changes that are compatible without any changes.

Apps targeting Android 12

category change compatibility abstract
1. user experience Custom notification appearance template unification Mandatory ❗ The content area of the user-defined notification is reduced to an area within the user-defined notification template, and the notification area is no longer completely covered
Picture in picture (PIP) interaction improvement recommend ⭐ Optimize user interaction in picture in picture (PIP) mode
Toast view improvements Adapted The system toast view text can display up to two lines, and the application icon is always displayed next to the text
2. security and privacy settings New Bluetooth runtime permissions (New) recommend ⭐ Introduce some new runtime permissions to better manage connections applied to nearby Bluetooth devices without requesting location information permissions
Sensor sample rate limit Adapted The system will limit the data refresh rate of some mobile sensors and position sensors
Apply sleep improvements Adapted Extended application sleep mechanism
Attribution marking improvement in data access audit Mandatory ❗ Attribution tags must be declared in the manifest file
ADB backup limit Adapted The data exported by ADB backup no longer contains application data by default
Explicitly specify the component exported property Mandatory ❗ Components that declare <intent-filter> filters must explicitly set the android:exported attribute
Explicitly specify pendingintent variability Mandatory ❗ Pendingintent must explicitly declare a mutable flag
Detect unsafe nested intent starts Adapted Strictmode detects unsafe nested intent starts
3. performance and battery Precise alarm permissions (New) Mandatory ❗ The application setting the AlarmManager precise alarm clock must declare the permission in the manifest
Foreground service startup restrictions Mandatory ❗ Except for a few cases, the application is forbidden to start the foreground service from the background
Notification of trampoline restrictions Mandatory ❗ Prohibit indirect start of target activity from notification trampoline

All applications

category change compatibility abstract
4. user experience Material you design language (New) Adapted New design language
Rich media content insertion (New) recommend ⭐ Apps can accept content from any source (clipboard paste, keyboard input, or drag and drop) from a unified location
Avif picture support (New) recommend ⭐ Support avif format pictures
App launch animation API splashScreen (New) Mandatory ❗ Support customized application to start transition animation
Widget desktop widget improvements recommend ⭐ Improve the appearance and behavior of widgets
Graphics API improvements recommend ⭐ New graphic effect
Overscroll overslip animation improvements Adapted Over slide animation changed to stretch and bounce effects
Notification improvement recommend ⭐ Add new notification style and security
HTTP deep link parsing improvements Adapted Adjusted the default parsing behavior of HTTP intent
Improvement of gesture navigation in full screen mode recommend ⭐ Added the mode that gesture navigation can be executed after one interaction
Screen size API change Mandatory ❗ The system introduces a new API to meet the needs of obtaining screen size on each device
Multi window mode standardization Mandatory ❗ In large screen devices, the system will enable multi window mode for all activities
Delayed display of front desk service notification Adapted Except for special cases, the front desk service notification will be delayed for 10 s
Activity lifecycle improvements Adapted Modify the return behavior of the root activity
Surface frame rate switching improvement recommend ⭐ API for introducing forced switching frame rate
5. security and privacy settings Privacy Information Center (new features) recommend ⭐ The privacy information center displays the access of all applications to sensitive information in the past time in the form of a timeline
Only rough location permission is supported (New) Mandatory ❗ Users can only grant apply fuzzy location permission
Microphone and camera toggle switch (New) Adapted The user can disable the camera or microphone permission on the whole device through the global switch
Microphone and camera indicators (New) Adapted When an app uses a microphone or camera, the status bar will be marked with an icon.
Clipboard access prompt (New) Adapted When an app accesses clip data from another app for the first time, a message box message will pop up
Hide apply overlay window (New) recommend ⭐ All visible system level floating windows can be hidden when the applied window is visible
App cannot close system dialog Mandatory ❗ Except in special cases, the application is prohibited from trying to close the system dialog box
Mask untrusted touch events Mandatory ❗ Mask events passed from windows of different applications
6. performance and battery Application standby partition improvement Adapted A new restricted standby partition is introduced

Sections 1-3 introduce the application behavior changes and new function updates with Android 12 as the target version. I summarize these updates into three parts:

  • 1. User experience (Android 12 as the target version)
  • 2. Security and privacy settings (target Android 12)
  • 3. Performance and battery (target Android 12)

1. user experience (Android 12 as the target version)

1.1 uniform custom notification appearance template

Android system notifications can be divided into two types: Standard notifications + custom notifications

  • Standard notice:Standard notices are based onNotificationCompat.Builder#setContentTitle()And other template API build notifications will eventually be displayed according to the preset view template. For example:

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

  • Custom notification:Custom notifications are based onNotificationCompat.Builder#setCustomContentView()And other API built notifications will eventually be displayed according to the layout customized by the developer, rather than according to the standard notification template.

Starting from the Android 12 system, the system has standardized the appearance and behavior of customized notifications. The content area of customized notifications is reduced to an area within the customized notification template, and the notification area is no longer completely covered. Therefore, if your application uses custom notifications, you need to make necessary tests and adjustments:

  • Layout adjustment:As the content area is reduced, the notification layout needs to be adjusted and tested;
  • Set up expanded Notifications:Since all notifications are expandable, you need to callNotificationCompat.Builder#setCustomBigContentView()Set the post deployment layout to ensure that the deployment and collapse states are consistent.

The following figure shows a unified custom notification template:

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

It can be seen that this change is that Google hopes that the customized notification can present a relatively consistent visual experience and reduce the compatibility problems on different devices.

1.2 PIP interaction improvement

Picture in picture mode is a multi window mode introduced in Android 8.0. It is most commonly used in video playback activities. It can open other applications during video playback without exiting and interrupting the current video. Currently, mainstream audio and video apps support picture in picture mode. You can search “picture in picture” in system settings to view it.This change is Google’s optimization of user interaction in the picture in picture mode, specific reference:

1.3 toast view improvement

In Android 12, the system toast view text can display up to two lines, and the application icon is always displayed next to the text. Relevant information:Message box overview

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table


2. security and privacy settings (Android 12 as the target version)

2.1 new Bluetooth runtime permissions (new functions)

Android 12 system introduces new runtime permissionsBLUETOOTH_SCANBLUETOOTH_ADVERTISEAndBLUETOOTH_CONNECTPermissions to better manage connections applied to nearby Bluetooth devices.

In the lower version, the application needs user authorization to connect with nearby Bluetooth devicesACCESS_FINE_LOCATIONPrecise location permission is actually an unreasonable design, because it is difficult for users to understand why Bluetooth connection is related to location information. From Android 12 system, access_ FINE_ Location precise location permission is optional. As long as the application does not derive physical location information through Bluetooth, it is no longer required to request. If not, you need to explicitly makeusesPermissionFlagsStatement:

<manifest>
    <!-- Include "neverForLocation" only if you can strongly assert that
         your app never derives physical location from Bluetooth scan results. -->
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN"
                     android:usesPermissionFlags="neverForLocation" />
    ...
</manifest>
  • New Bluetooth permission system (with Android 12 as the target version):

    • BLUETOOTH_ Scan: allows searching for nearby Bluetooth devices;
    • BLUETOOTH_ Advertise: allows the current device to be exposed to other Bluetooth devices;
    • BLUETOOTH_ Connect: allows the current device to connect to other Bluetooth devices;
    • ACCESS_ FINE_ Location (optional): allows the derivation of device location information from Bluetooth information.
  • Old Bluetooth permission system:

    • Bluetooth: allows Bluetooth related interaction;
    • ACCESS_ FINE_ Location (required): it is allowed to derive device location information from Bluetooth information. In Android 9 or below, access can be used_ COARSE_ Location override.

In addition, bluepath_ Scan and other permissions are nearby_ Part of the device permission group near devices. Request permission for the permission group. The permission granting dialog box will prompt the user to approve access to nearby devices.

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

It can be seen that this time, Google hopes that the permission granted to connect Bluetooth devices can give users a more accurate description of permission functions.

Relevant information:

2.2 sensor sampling rate limit

Most Android devices have built-in sensors that measure motion, screen orientation, and various environmental conditions. These sensors can provide highly accurate raw data. In order to protect potentially sensitive information about users, the Android 12 system will limit the refresh rate of data from some mobile sensors and location sensors.

Relevant information:Sensor overview——Official documents

2.3 Application sleep improvement

Android 11 introduces the application hibernation mechanism. If the user does not interact with the application for several months, the system will put the application in the hibernation / hibernation state. Android 12 extends the application hibernation mechanism:

  • Android 11: reset the granted runtime sensitive permissions;
  • Android 12: reset the granted runtime sensitive permissions; Unable to run the task from the background; Unable to receive push notification; The application cache file will be deleted.

Relevant information:App sleep——Official documents

2.4 attribution mark improvement in data access audit

Android 11 introduces the data access audit API. Developers can add attribution marks in the code location where the application accesses the user’s privacy data, and registerAppOpsManager.OnOpNotedCallbackmonitor. This function provides monitoring for calling private data. No matter the code in the application layer or the dependent library, as long as it accesses private data (dangerous permissions), it will call back. From the Android 12 system, attribution tags must be declared in the manifest file, for example:

<manifest ...>
    <!-- The value of "android:tag" must be a literal string, and the
         value of "android:label" must be a resource. The value of
         "android:label" should be user-readable. -->
    <attribution android:tag="sharePhotos"
                 android:label="@string/share_photos_attribution_label" />
    ...
</manifest>

Relevant information:Data access audit——Official documents

2.5 ADB backup restrictions

To protect private application data, Android 12 has changedadb backupThe default behavior of the command. The data exported by ADB backup no longer contains application data by default. If the development phase needs to rely on the application data exported by ADB backup, you can set android:debuggable to true in the manifest file to export the application data.

2.6 explicitly specify the exported attribute of the component

Component propertiesandroid:exportedUsed to set whether the component supports interaction with other applications. If exported is false, the component is not allowed to be started by other applications. Generally, the exported attribute defaults to false unless the component declares<intent-filter>Filter (that is, it supports implicit startup), the exported property defaults to true. Starting from the Android 12 system, components that declare <intent-filter> filters must explicitly set the android:exported attribute. For example:

<service android:name="com.example.app.backgroundService"
         android:exported="false">
    <intent-filter>
        <action android:name="com.example.app.START_BACKGROUND" />
    </intent-filter>
</service>

Otherwise, an error will be reported when compiling the application:

Manifest merger failed : Apps targeting Android 12 and higher are required \
to specify an explicit value for android:exported when the corresponding \
component has an intent filter defined.

If you use a lower version of the Android gradle plug-in, although it can be compiled successfully, an error will be reported during installation:

Installation did not succeed.
The application could not be installed: INSTALL_FAILED_VERIFICATION_FAILURE

It can be seen that the idea behind this change is “don’t trust the default value”, because the default value that does not meet the expectations will lead to more serious risks。 For example, due to the negligence of the developer, a component that originally did not allow external applications to start did not explicitly declare android:exported= “false”, but it happened that the component declared the <intent-filter> filter, so there was a security risk due to the impact of the default value. By forcing developers to explicitly declare the value of android:exported for components declaring <intent-filter> filters, the security risk of the default value can be avoided. For the same reason, do not trust the default values when connecting to external systems. For example, the default values of network request parameters can be transmitted as soon as possible.

2.7 explicitly specifying pendingintent variability

In order to make the handling of pendingintent more secure, Android 12 requires that pendingintent must explicitly declare a variability flag, namelyFLAG_MUTABLEOrFLAG_IMMUTABLE。 Previously, pendingintent was variable by default.

2.8 detect unsafe nested intent startup

Android 12 introduces aStrictModeCheck rules for detecting unsafe nested intent starts. Strictmode mode mode is familiar to everyone. Here we explain why nested intent startup is unsafe.

For example, the expected effect of the developer is that the client app requests a service from the provider app and wants to call back to the clientcallbackactivity of the client app after the request is completed. Then, the most direct method is to nest the intent of starting clientcallbackactivity into the intent of starting apiservice as a parameter. For example:

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

At first glance, there is no problem, but in fact, there are two hidden security risks in this implementation method:

  • Client App:Because clientcallbackactivity is started from another application provider app, it must be exposed as exported. This means that in addition to the provider app, other malicious applications on the device can also start clientcallbackactivity;
  • Provider App:Because the nested intent is started in the context of the provider app, the malicious application attacker app can nest any activity of the provider app in it, even if the private non exported activity is started, which makes the provider app vulnerable.

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

The solution is to use pendingintent instead of nested intent. Pendingintent is the packaging container of intent, which is also similar to a nested intent. However,Many small partners simply think that pendingintent is only an intent that is delayed to be processed. The difference between the two is only in the time dimension, which is one-sided.

The main function of pendingintent is to authorize external applications to execute and use nested intent as this application.It’s a bit awkward. In our example, after the client app exposes the intent that starts the clientcallbackactivity to the provider app, but when the provider app uses the pendingintent, the system will use the nested intent as the context of the client app.

PendingIntent pendingIntent = PendingIntent.getActivity(application, 0, resultIntent, 0);

Now, let’s review whether there are any risks:

  • Client App:Because pendingintent uses nested intent as the identity of client app, clientcallbackactivity no longer needs to be exposed as exported;
  • Provider App:Pendingintent uses nested intents as the client app / attacker app, and they do not have permission to access the non exported apisensitiveactivity of the provider app.

Relevant information:Android nested intent——Official blog posts


3. performance and battery (Android 12 as the target version)

3.1 accurate alarm clock permission (new function)

Android 12 system introduces new permissionsandroid.permission.SCHEDULE_EXACT_ALARM, the application that sets the AlarmManager precise alarm clock must request schedule in the manifest_ EXACT_ Alarm permission. In addition, a new API has been added——canScheduleExactAlarms()To check the permission status of the application’s accurate alarm clock.

Relevant information:Set the repeat alarm time

3.2 foreground service startup restrictions

Android 12 restricts the application from starting the foreground service from the background, exceptExemption from background start restrictionIf an application attempts to start the foreground service while running in the background, the system will throwForegroundServiceStartNotAllowedExceptionException. Applications can use the newly introducedExpedited operation(expedited job) to replace the previous practice.

Tips:If an application callsContext.startForegroundService()To start the foreground service owned by another app, these restrictions only apply to the case where both apps are targeted at Android 12 or later.

3.3 notification of trampoline restrictions

Notification trampoline refers to the use of a broadcast receiver or service to indirectly start the target activity (after the user interacts with the notification, the application starts the service or broadcast receiver as an intermediary, and then starts the target activity). The Android 12 system restricts the notification of trampoline. When an application attempts to start an activity from the notification trampoline, the system will intercept the startup behavior:

Indirect notification activity start (trampoline) from PACKAGE_NAME, \
this should be avoided for performance reasons.

If your app uses notification trampoline, you need to switch to the normal pendingintent mode.


Sections 4-6 introduce the application behavior changes and new function updates for all applications. I summarize these updates into three parts:

  • 4. User experience (all apps)
  • 5. Security and privacy settings (all apps)
  • 6. Performance and battery (all applications)

4. user experience (all applications)

4.1 material you design language (new function)

Android 12 introduces aMaterial YouThe new design language of (the redevelopment of material design) can help build more personalized and exquisite applications.

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

4.2 rich media content insertion (new function)

Android 12 system introduces a unified API, which enables applications to accept content from any source (clipboard paste, keyboard input or drag and drop operation) from a unified location. For example:

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

Relevant information:Receive rich media content——Official documents

4.3 support avif pictures (new function)

Android 12 introduced support for pictures using the AV1 picture file format (avif). Avif is a container format that uses AV1 encoded pictures and picture sequences. Avif uses the intra coding content of video compression. Compared with previous image formats (such as JPEG), this format can significantly improve the image quality under the same file size.

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

Relevant information:AVIF has landed——By Jake Archibald

4.4 application startup animation API splashScreen (new function)

Starting from the Android 12 system, during the cold start and warm start of all applications, the system will use the new splashScreen API to start the application startup animation. In addition to the platform API, Google also provides a compatible library API:androidx.core.splashscreen

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

Before the splashScreen API, we usually used the background map of splashactivityandroid:windowBackgroundTo achieve the transition effect of application startup, which is familiar to everyone. If you do not do any adaptation, you will have different effects on Android 12 according to the configured windowsbackground resource value:

  • Windowsbackground adopts@Color/ monochrome, the system will use the monochrome and the application startup icon to form the startup effect, which may be inconsistent with the expected effect;
  • Windowsbackground adopts@Drawable/ picture, the system will continue to use the image to form a startup effect. This experience is consistent with that of the lower version system.

Therefore, if your application uses windowsbackground as the image resource, you will have no problem adapting it. If you need to upgrade the startup effect, it is recommended to refer to the following materials:

It can be seen that this change to Google is intended to improve the transition experience when the next application is launched, and also give developers more customized imagination.

4.5 widget desktop widget improvement

Android 12 improves the existing widgets API, making them more practical, more beautiful, and easier to find. See the following information for relevant changes:

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

Relevant information:

4.6 graphic API improvement

  • Fillet: Android 12 introduces a new fillet APIRoundedCorner
    AndWindowInsets.getRoundedCorner(int position), which can be provided to view to realize fillet effect;
  • Filters: Android 12 adds a new filter APIRenderEffectCommon picture effects (such as ground glass, color filter, Android shader effect and more) can be implemented for view.

    view.setRenderEffect(RenderEffect.createBlurEffect(radiusX, radiusY, SHADER_TILE_MODE))

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

4.7 overscroll over slide animation improvements

Android 12 has modified the animation effect of scrollable controls’ overscroll on the edge, from the edge lighting effect in the lower version to the stretching and bouncing effect. This edge over sliding effect can be turned off in two ways:

  • set upandroid:overScrollMode=”never”
  • set upView#setOverScrollMode(View.OVER_SCROLL_NEVER)

4.8 notification of improvement

  • Telephone notification: starting from Android 12 system, a new telephone notification style has been addedNotification.CallStyle
  • Rich image support: starting from Android 12 system, the application canMessagingStyle()Animated pictures are provided in the notification to enrich the notification experience of the application. In addition, the application now allows users to send picture messages when replying to messages from the notification bar;
  • Device unlocking guarantee: from Android 12 system, applications cansetAuthenticationRequired(true), the system requires the user to unlock the device before executing the notified pendingintent, which adds a layer of security for sensitive operations.

4.9 HTTP deep link parsing improvement

The Android system supports the association between deep links and application behaviors through deep link or Android App link. In practice, links are based on URI format, for example:

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

Starting from Android 12 system, the system adjusted the default parsing behavior of HTTP intent. In the lower version, if the HTTP link does not hit any deep link / APP link matching rules, the system will open the application selection dialog box; Now the system will open the link directly through the default browser (because the link itself is an accessible web address)

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

Relevant information:

4.10 improvement of gesture navigation in full screen mode

Full screen mode refers to the application making the most of the screen space to display content, so that users can get the best experience. Common scenes such as video, games, presentations, etc.

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

The full screen mode will hide the status bar, navigation bar and other system bars, which means that users cannot easily interact with the system bar. Therefore, the system defines the system bar behavior in the following full screen mode, usingWindowInsetsControllerCompat.setSystemBarsBehaviorset up:

  • BEHAVIOR_SHOW_BARS_BY_TOUCHMode, when the user clicks any position on the screen, the system bar will be redisplayed. This mode is suitable for scenarios where the user will not have a lot of interaction with the screen;
  • BEHAVIOR_SHOW_BARS_BY_SWIPEMode, the system bar is displayed when the user slides from the edge of the hidden system bar. For example, sliding up from the bottom edge of the screen will redisplay the system navigation bar. This mode is suitable for scenarios where users need to interact with the screen in a large amount, such as games, reading, etc. using this gesture with stronger intention can avoid the conflict between system bar interaction and application interaction;
  • BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPEMode. When the user slides from the edge of the hidden system bar, the system bar will be temporarily displayed and automatically hidden again after a short period of time. The system bar will not squeeze the application content, but cover the upper layer of the application in a translucent way.

Android 12 system integrates the existing mode, behavior_ SHOW_ BARS_ BY_ Touch and behavior_ SHOW_ BARS_ BY_ Swipe these two behaviors have been abandoned and behavior has been added_ Default behavior.

  • BEHAVIOR_DEFAULTMode: when the user slides from the edge of the hidden system bar, the system bar is displayed, which is similar to behavior_ SHOW_ BARS_ BY_ Swipe is similar. The most important thing is that the full screen navigation gesture can take effect directly, regardless of whether the system navigation bar is visible or not. In other words, behavior_ The default behavior allows users to swipe once to perform gesture navigation, while on Android 11, it requires two swipes.

Relevant information:Enable full screen mode

4.11 screen size API change

Android 11 system is obsoleteDisplay.getSize & Display.getMetrics, and continue to be abandoned in Android 12Display.getRealSize & Display.getRealMetrics。 Android devices have many different shapes (such as large screen devices, tablets and collapsible mobile phones). In order to adapt to the needs of obtaining screen size on each device, the system introduces windowmetrics API.

4.12 multi window mode standardization

The Android 7 system introduces the multi window mode, which allows multiple applications to be displayed on the screen at the same time. At present, there are three multi window modes:

  • Split screen mode:Display two applications side by side or up and down;
  • Picture in picture mode:Display the application in a superimposed small window;
  • Free window mode:Display the application in a movable and resizable window;

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

Starting from Android 12 system, multi window mode will become the standard behavior on large screen devices, and theresizeableActivityConfiguration will be ignored. The details are as follows:

  • Android 7:Mobile devices support split screen mode, TV devices support picture in picture mode, and larger device manufacturers can choose to enable free window mode. Developers can set android:resizeableactivity= “false” to disable the multi window mode to ensure that the activity is always displayed in an exclusive way;
  • Android 8:Mobile devices also support picture in picture mode;
  • Android 12:In small screen devices (SW < 600dp), the system determines whether the activity enables multi window mode according to the resizeableactivity configuration. In large screen devices, the system ignores the resizeableactivity configuration and enables multi window mode for all activities. Before that, if the activity to be operated by the user does not support multiple windows, the user can only exit the window first and then come back, and the experience will be interrupted.

It can be seen that this time, Google hopes that the multi window mode under the large screen device will become the standard behavior and realize the experience closed loop under the multi window mode

4.13 delayed display of front desk service notice

The foreground service (the service started by startforegroupservice) will display a system notification so that the user application is executing tasks and consuming system resources, even if the application has exited to the background. From the Android 12 system, the foreground service notification will be delayed for 10 s, unless some services need to display the notification immediately.

The following are the cases where notifications are displayed immediately:

  • 1. Foreground service notification callNotificationCompat.Builder#setForegroundServiceBehavior(FOREGROUND_SERVICE_IMMEDIATE)Modified the display behavior;
  • 2. Foreground service notification callNotificationCompat.Builder#addAction()Operable buttons are configured;
  • 3. Foreground service notification callNotificationCompat.Builder#setCategory()Configure as category_ CALL、CATEGORY_ Navigation or category_ TRANSPORT;
  • 4. Front deskforegroundServiceTypeThe values are mediaplayback, mediaprojection or phonecall.

It can be seen that this change is intended to simplify the user perception of the short-term foreground service. Since the service stopped soon, there is no need to notify users to notice.

Relevant information:

4.14 activity life cycle improvement

Starting from Android 12, the system has modified the default behavior of the activity task root activity when processing the “return key”. In the old version, the return key will execute the finish activity, while starting from Android 12, the task stack will be switched to the background. After that, the user will return to the application to execute the hot start. The hot start of the application is much simpler, and the system only works to restore the activity to the foreground.

Activity.java

public void onBackPressed() {
    if (mActionBar != null && mActionBar.collapseActionView()) {
        return;
    }

    FragmentManager fragmentManager = mFragments.getFragmentManager();

    if (!fragmentManager.isStateSaved() && fragmentManager.popBackStackImmediate()) {
        return;
    }
    if (!isTaskRoot()) {
        // If the activity is not the root of the task, allow finish to proceed normally.
        finishAfterTransition();
        return;
    }
    //The above Android 12 is the same as the old version, with the difference in the following sentence:
    try {
        // Android 11
        // Inform activity task manager that the activity received a back press
        // while at the root of the task. This call allows ActivityTaskManager
        // to intercept or defer finishing.
        ActivityTaskManager.getService().onBackPressedOnTaskRoot(mToken,
                new IRequestFinishCallback.Stub() {
                    public void requestFinish() {
                        mHandler.post(() -> finishAfterTransition());
                    }
                });
        // Android 12
        // Inform activity task manager that the activity received a back press while at the
        // root of the task. This call allows ActivityTaskManager to intercept or move the task
        // to the back.
        ActivityClient.getInstance().onBackPressedOnTaskRoot(mToken,
                new RequestFinishCallback(new WeakReference<>(this)));
    } catch (RemoteException e) {
        finishAfterTransition();
    }
}

It can be seen that this time, Google hopes to return throughkey“Exiting applications can recover applications from a hot start faster than restarting applications from a cold or warm start.

4.15 surface frame rate switching improvement

Android 11 system introduces a surface frame rate switching APIsetFrameRate()But this API does not always work. Since the screen that does not support seamless frame rate switching will have a black screen for oneortwo seconds when switching the frame rate, the system will intercept this behavior. If the screen does not support seamless switching, the original frame rate will continue to be used even if the application calls setframerate().

The Android 12 system introduces an API for forced frame rate switching, which is more advantageous for frame rate switching of long video content, because the experience improvement brought by the appropriate frame rate has exceeded the experience loss brought by the lack of seamless switching.

//Check whether seamless frame rate switching is supported
val refreshRates = this.display?.mode?.alternativeRefreshRates
val willBeSeamless = Arrays.asList<FloatArray>(refreshRates).contains(newRefreshRate)

//Switch frame rate, even if the screen does not support seamless transition
surface.setFrameRate(newRefreshRate, FRAME_RATE_COMPATIBILITY_FIXED_SOURCE, CHANGE_FRAME_RATE_ALWAYS)
  • CHANGE_FRAME_RATE_ALWAYS:Always switch the frame rate, even if the screen does not support seamless transition;
  • CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:Switch the frame rate only if the screen supports seamless transition (old version behavior).

5. security and privacy settings (all apps)

5.1 Privacy Information Center (new function)

The Android 12 system introduces the privacy information center function in the system settings, which can enable users to better understand the behavior of applications accessing data. The privacy information center displays the access of all applications to sensitive information such as microphones, cameras or locations in the past time in the form of a time axis.

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

In addition, the system defines a new intent operationACTION_VIEW_PERMISSION_USAGE_FOR_PERIODFrom the privacy information center, you can explain to users why applications need to access these privacy information. To support this function, the application needs to define an activity and declare that intentfilter is associated with this action, for example:

<!-- android:exported required if you target Android 12. -->
<activity android:name=".DataAccessRationaleActivity"
          android:permission="android.permission.START_VIEW_PERMISSION_USAGE"
          android:exported="true">
       <!-- VIEW_PERMISSION_USAGE shows a selectable information icon on
            your app permission's page in system settings.
            VIEW_PERMISSION_USAGE_FOR_PERIOD shows a selectable information
            icon on the Privacy Dashboard screen. -->
    <intent-filter>
       <action android:name="android.intent.action.VIEW_PERMISSION_USAGE" />
       <action android:name="android.intent.action.VIEW_PERMISSION_USAGE_FOR_PERIOD" />
       <category android:name="android.intent.category.DEFAULT" />
       ...
    </intent-filter>
</activity>

Relevant information:Explain access to sensitive information

5.2 only rough location permission can be granted (new function)

The Android system supports two precision levels of location information, and each corresponds to a permission. Although there are two precision levels of permissions, because they are in the same permission group, as long as an application requests to grant one permission, the other permission will be granted automatically.

  • Rough position:Position value accurate to 3 square kilometers, request access_ COARSE_ Location permission can be obtained;
  • Exact location:Position value accurate to within 50m, request access_ FINE_ Location permission can be obtained.

However, from the Android 12 system, this rule no longer holds. From the Android 12 system, users can only grant access to fuzzy locations_ COARSE_ Location permission, even if the application requests precise location access_ FINE_ Location permission.

For example, we request access through the following code_ FINE_ Location permission: the permission request pop-up window on Android 12 system will give users two options:Precise precise positionandApproximate position。 If the user chooses to grant rough location, the final application obtains access instead_ COARSE_ Location permission instead of the access requested at the beginning_ FINE_ Location permission, and the application can only obtain rough location information.

val locationPermissionRequest = registerForActivityResult(
    ActivityResultContracts.RequestPermission()
) { isGrant ->

    Log. I ("permission", "isgrant: $isgrant")
    if (PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
        Log. I ("access\u court\u location is grant")
    }
    if (PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
        Log. I ("permission", "access\u fine\u location is grant")
    }
}

findViewById<View>(R.id.tv).setOnClickListener {
    locationPermissionRequest.launch( Manifest.permission.ACCESS_FINE_LOCATION)
}

Output log:

I/ permission: isgrant: false
I/ permission: access_ COARSE_ LOCATION is Grant

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

Starting from Android 12, you should pay attention to the following problems when requesting location permissions. If you don’t pay attention, there will be compatibility problems:

  • When requesting location permission, you should also request access_ FINE_ Location permission and access_ COARSE_ Location permission, if the application only requests access_ FINE_ Location permission, the system will directly ignore the request. If the application takes Android 12 or higher as the target version, the system will prompt an error in logcat:

    ACCESS_FINE_LOCATION must be requested with ACCESS_COARSE_LOCATION.

    Tip: I have measured on the pixel simulator that there are no “ignore request” and “error prompt” described in the document, but it is better to follow the official document.

  • Even if the user has granted the precise location permission, the user can still enter the system settings and directly modify to the rough location permission. After modification, the system will automatically kill the process.
  • To better respect user privacy, try to only request access_ COARSE_ Location permission, because rough location information can meet most application scenarios. Request access only_ COARSE_ For location permission, the authorization pop-up window has only one option:

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

  • If your application scenario really needs to request access_ FINE_ Location permission, then you can request access again at the same time_ FINE_ Location and access_ COARSE_ Location permission. Since the user has previously granted the rough location permission, the system pop-up window will change to ask whether to upgrade to the precise location permission:

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

A small partner found that on some Android 12 mobile phones, the behavior of requesting location permission is no different from that of the lower version, because some manufacturers’ systems have not fully implemented this function. Take Xiaomi MIUI 13.0.5.0 as an example, the fuzzy positioning function needs to be turned onSystem settings - Privacy Protection Lab - fuzzy positioningOption can be enabled. Moreover, after the actual measurement on the system, I found that even if the user only grants access_ COARSE_ Location permission, another access_ FINE_ The location permission will also be granted at the same time, which is outrageous. No wonder it is still in the laboratory.

It can be seen that this change is that Google hopes to guide developers to use low-precision location information as much as possible to improve the protection of users’ privacy.

Relevant information:

5.3 microphone and camera switch (new function)

Starting from Android 12 system, users can disable camera or microphone permissions on the whole device through a global switch. When the application requests permission for the camera or microphone, the system will pop up. This switch is different in different manufacturers’ systems. For example, the Xiaomi system is placed onPhone off - stealth mode

Fully understand the system update and collect this Android 12 (s) version adaptation self-examination table

5.4 microphone and camera indication (new function)

Starting from Android 12, when an app uses a microphone or camera, there will be an icon mark in the status bar.

5.5 clipboard access prompt (new function)

In Android 12 and later, when an application calls for the first timegetPrimaryClipWithAccess clip data from another app“), a message box will pop up to prompt the user that the application has the behavior of accessing the clipboard.

5.6 hide application overlay window (new function)

Android 12 system introduces hidden type_ APPLICATION_ Functions of the overlay window. DeclarationHIDE_OVERLAY_WINDOWSAfter permission, the application can callsetHideOverlayWindowsIndicates that all visible types are hidden when the applied window is visible_ APPLICATION_ Overlay window. For example, when displaying sensitive pages (such as transactions), the application can choose to hide other floating windows.

5.7 the application cannot close the system dialog box

In order to strengthen the control when users interact with applications and systems, Android 12 system has been abandonedACTION_CLOSE_SYSTEM_DIALOGSIntent operation. When an application attempts to close the system dialog box by using, exceptSome special casesIn addition, the system will intercept:

  • Take Android 12 or higher as the target version: the system will throw a SecurityException;
  • Take Android 11 or lower as the target version: the system will not execute intent and will prompt in logcat:

    E ActivityTaskManager Permission Denial: \
    android.intent.action.CLOSE_SYSTEM_DIALOGS broadcast from \
    com.package.name requires android.permission.BROADCAST_CLOSE_SYSTEM_DIALOGS, \
    dropping broadcast.

5.8 shield untrusted touch events

Screen application is the main way for users to interact with applications. In order to improve the intuition and security of touch interaction, Android 12 system will shield events transmitted from different application windows. Therefore, this change mainly affects the application that allows touch events to penetrate the window. For example, type is declared_ APPLICATION_ Overlay and flag_ NOT_ Floating window of touchable.

See relevant data for detailed analysis:Behavior change | untrusted touch events in Android 12——Official blog posts


6. performance and battery (all applications)

6.1 application standby partition improvement

The app standby buckets application standby partition is a battery management function introduced by Android 9. The system will sort applications according to their recent use and frequency, and place them in different partitions. More active applications will be assigned to higher priority partitions, while the jobs, alarm clocks or FCM of applications in lower priority partitions will have certain restrictions. Android 12 system introduces a new partition – “restricted” standby partition:

  • Active: currently in use or just recently used;
  • Worksets: regular use;
  • Commonly used: often used, but not every day;
  • Rarely used: infrequently used;
  • Limited: the application consumes a lot of resources or shows bad behavior
  • Never used: installed but never run.

In the old version, standby partitions were only sorted according to the activity of applications, but now there is a dimension that introduces resource utilization.It can be seen that this change is Google’s hope to increase the restrictions on applications that consume a lot of system resources.

Note: these restrictions only apply to the case that the equipment is powered by battery; The system does not impose these restrictions on the application during device charging.

Relevant information:Application standby partition——Official documents


7. summary

Pay attention to me and let you know more. I’ll see you next time.

The following changes are relatively unpopular and of low practical value, and will not be displayed temporarily:

  • Behavior change – target 12 – user experience – camera preview improvement on large screen devices & rich feedback experience & appsearch & Game Mode & recent website sharing (pixel only)
  • Behavior change: target 12 – modern samesite cookies in WebView & Backup and Recovery & connectivity & Vendor & updated non SDK interface restrictions
  • Behavior change: all applications – Security and privacy settings – permissions package visibility & bouncycastle implementation removed
  • Behavior change: all apps – Security and privacy settings-
  • Behavior change: all applications – Media & Camera & graphics and pictures & connectivity & updated non SDK interface restrictions

reference material

Your praise means a lot to me! Wechat search official account [pengxurui], I hope you can discuss technology together and find like-minded friends. See you next time!