Android 13 Changes and Adaptation Guide

insert image description here

Preparation

targetSdkVersionStart by raising the sum to 33 in our project compileSdkVersion.

Affects all apps on Android 13

1. Restricted notifications

Effect on newly installed apps:

When a user installs your app on a device running Android 13 or higher, your app's notifications are turned off by default. Your app will not be able to send notifications until you request a new permission and the user grants your app that permission.

  • If your app targets Android 13 or higher, your app will have full control over when the permission dialog is displayed. This is an opportunity to encourage users to grant it by explaining why your app needs the permission.
  • If your app targets 12L (API level 32) or lower, when your app starts an activity for the first time after you create a notification channel, or when your app starts an activity and then creates its first notification When selecting a channel, the permission dialog is displayed. This is usually at app startup.

Impact on existing app updates:

To minimize interruptions related to notification permissions, when users upgrade their devices to Android 13 or higher, the system automatically pre-grants the corresponding permissions to all eligible apps. In other words, these apps can continue to send notifications to the user without the user seeing a runtime permission prompt.

Adaptation method:

Apps targeting Android 13 or higher need to manifestdeclare POST_NOTIFICATIONSpermissions in the application file and go through a process similar to requesting other runtime permissions.

<manifest ...>
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
</manifest>

Before requesting permission, you can use areNotificationsEnabled()the method to check whether the user has notifications enabled. Do permission application on Android 13, and Android 13 can guide the setting page to open.

The official documentation recommends waiting to ask for permissions until the user is familiar with your app. Here are a few suitable times to display notification permission prompts:

  • When the user taps the "Alert Bell" button.
  • When a user chooses to follow someone else's social media account.
  • When a user submits a delivery order.

The diagram below is a suggested user-driven workflow for requesting notification permissions. Showing the intermediate screen is only shouldShowRequestPermissionRationale()necessary if returns true.

insert image description here

2. The intent filter will block unmatched intents

When your app sends an exported component of another app that targets Android 13 or higher intent, the system delivers this only if it matches an element intentin the receiving app . In other words, all mismatches are blocked except for the following:<intent-filter>intentintent

  • The target component doesn't declare any <intent-filter>.
  • Sent within the same app intent.
  • sent by the system intent.
  • Sent by a process with ROOT privileges intent.

If the receiving app is upgraded to Android 13 or higher, intentall content originating from the external app is passed to the exporting component only if it matches its declared element intent, regardless of the sending app's target SDK version.

So we need to check whether other apps are started or broadcast through Intent in the application, and at the same time, check actionwhether datathe information such as , etc. is accurate.

Affects apps targeting Android 13 or higher

1.GestureDetector

After upgrading to 33, it was found that the compilation failed. At first glance, the interface implemented by kotlin GestureDetector.OnGestureListenerreports an error, and the parameters onScrollof the prompt method MotionEventwill not be empty. The reason is that the code here on Android 13 has one more @NonNullannotation.

insert image description here

I thought it would be normal to delete the empty "?", but found that an error will be reported on a low-version phone:

Fatal Exception: java.lang.NullPointerException: 
Parameter specified as non-null is null: method android.view.GestureDetector.onTouchEvent, parameter e1

Because on low-version mobile phones, the value obtained here MotionEventis empty. But in kotlin, when the variable is not empty, it will use checkNotNullParametermethod verification, if it is null, the above exception will occur.

insert image description here

So if you implement it in java, this problem will not exist. Then one of the solutions is to switch to java implementation. Or it can be added @Suppress("NOTHING_TO_OVERRIDE", "ACCIDENTAL_OVERRIDE")so that no checkNotNullParameterverification code will be generated.

If there are similar problems during the adaptation process, don't blindly delete "?". Need to pay attention to the operation of the lower version.

2. Read media file permissions

For apps whose target version is Android 13, the permissions are refined READ_EXTERNAL_STORAGE, use READ_MEDIA_IMAGE, READ_MEDIA_VIDEO, and READ_MEDIA_AUDIOreplace READ_EXTERNAL_STORAGE.

If the user has previously granted your app READ_EXTERNAL_STORAGEpermission, the system will automatically grant these three granular media permissions to your app.

Adaptation instructions:

<manifest ...>
    <!-- 按需添加 -->
    <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
    <uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
    <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
                     android:maxSdkVersion="32" />
    <application ...>
        ...
    </application>
</manifest>

The code part can make a judgment, for example:

String requestPermission;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    
    
    requestPermission = Manifest.permission.READ_MEDIA_IMAGES;
} else {
    
    
    requestPermission = Manifest.permission.READ_EXTERNAL_STORAGE;
}

In addition, the documentation suggests that if your application only needs to access images, photos, and videos, you can consider using the photo picker instead of the declaration READ_MEDIA_IMAGESand READ_MEDIA_VIDEOpermissions.

3. Access to nearby Wi-Fi devices is limited

Apps that target Android 13 (API level 33) or higher and manage Wi-Fi connections must request the NEARBY_WIFI_DEVICESruntime permission. This permission makes it easier for apps to access nearby Wi-Fi devices; on previous versions of Android, these apps needed to declare the ACCESS_FINE_LOCATIONpermission.

API methods that require NEARBY_WIFI_DEVICESpermissions:

  • WifiManager:startLocalOnlyHotspot()
  • WifiAwareManager:attach()
  • WifiAwareSession:publish()subscribe()
  • WifiP2pManager:addLocalService()connect()createGroup()discoverPeers()discoverServices()requestDeviceInfo()requestGroupInfo()requestPeers()
  • WifiRttManager:startRanging()

Adaptation instructions:

<manifest ...>
    <uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES"
                     android:usesPermissionFlags="neverForLocation" />

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
                     android:maxSdkVersion="32" />
</manifest>
  • If your app will not infer physical location via the Wi-Fi API, set usesPermissionFlagsthe property to neverForLocation. Also ACCESS_FINE_LOCATIONset the highest SDK version of the permission to 32
  • If you use WifiManageror , Android 13 still needs permission, so remove getScanResults()it .startScan()ACCESS_FINE_LOCATIONandroid:maxSdkVersion="32"

4. Advertising ID

Apps that use the Google Play Services Advertising ID and target Android 13 (API level 33) and higher must declare the general AD_ID permission in their manifest file, as follows:

<manifest ...>
    <uses-permission android:name="com.google.android.gms.permission.AD_ID"/>

    <application ...>
        ...
    </application>
</manifest>

If your app targets Android 13 or higher and doesn't declare this permission, the advertising ID is automatically removed and replaced with a string of zeros.

5. Disposal method

  • PackageManagerIn the getPackageInfo, getApplicationInfo, resolveActivityand other methods.

Take the commonly used getPackageInfomethod as an example:

 public static PackageInfo getPackageInfoCompat(PackageManager packageManager, String packageName, int flag)
        throws PackageManager.NameNotFoundException {
    
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    
    
        return packageManager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(flag));
    } else {
    
    
        return packageManager.getPackageInfo(packageName, flag);
    }
}
  • IntentIn getSerializableExtra, getParcelableExtraand Bundlein getSerializable, getParcelableand other methods.

To getParcelableExtraillustrate:

public static <T extends Parcelable> T getParcelableExtraCompat(Intent intent, String name, Class<T> clazz) {
    
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    
    
        return intent.getParcelableExtra(name, clazz);
    } else {
    
    
        return intent.getParcelableExtra(name);
    }
}

If your code is written in Kotlin, of course, this method can also be implemented with Kotlin's extension method for easy replacement.

  • WebSettingssetAppCacheEnabledThe , setAppCacheMaxSize, methods in setAppCachePathare removed.

    setAppCacheEnabled(false)can be setCacheMode(WebSettings.LOAD_NO_CACHE)substituted.

    setAppCacheEnabled(true)can be setCacheMode(WebSettings.LOAD_DEFAULT)substituted.

  • For apps targeting Android 13 (API level 33) or higher, the method WebSettingsin setForceDarkis deprecated and calling this method has no effect.

    WebView now always isLightThemesets media queries based on the app's theme attributes prefers-color-scheme. In other words, if isLightThemetrue or not specified, prefers-color-schemeis light; otherwise, dark. This behavior means that the light or dark styling of the web content is automatically applied (if the content supports applying themes).

    For most apps, the new behavior should automatically apply the appropriate app styles, however, you should test your app to check for situations where you might have manually controlled the dark mode setting.

    If you still need to customize your app's color theme behavior, use setAlgorithmicDarkeningAllowed()the method instead. For backward compatibility with previous Android versions, we recommend using the equivalent setAlgorithmicDarkeningAllowed()method in AndroidX.

Other new features and APIs

1. Export context registered receivers more safely

Android 13 allows you to specify whether specific broadcast receivers in your app should be exported and visible to other apps on the device. If you export a broadcast receiver, other apps will be able to send unprotected broadcasts to your app. This export configuration is available in apps targeting Android 13 or higher and helps prevent a major source of app vulnerabilities. In previous versions of Android, any app on the device could send unprotected broadcasts to a dynamically registered receiver unless that receiver was protected by a signing permission.

Apps targeting Android 13 or higher must specify a RECEIVER_EXPORTEDor RECEIVER_NOT_EXPORTED. Otherwise, the system will throw when you try to register the broadcast receiver SecurityException.

Caused by: java.lang.SecurityException: com.xxx.xxx: One of RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED should be specified when a receiver isn't being registered exclusively for system broadcasts

Of course, this is not currently mandatory, and needs to be enabled in Developer Options -> Application Compatibility Changes DYNAMIC_RECEIVER_EXPLICIT_EXPORT_REQUIRED. This security enhancement is disabled by default, so it has no impact for now.

Adaptation method:

// 这个广播接收器能够接收来自其他应用程序的广播。
context.registerReceiver(sharedBroadcastReceiver, intentFilter,
                    RECEIVER_EXPORTED);
// 这个私有广播接收器不能够接收来自其他应用的广播。
context.registerReceiver(privateBroadcastReceiver, intentFilter,
                    RECEIVER_NOT_EXPORTED);

Because our project previously replaced ordinary broadcasting with local broadcasting ( LocalBroadcastManager), it will not be affected.

2. Predictive Back Gestures

Android 13 (API level 33) introduces predictive back gestures for Android devices such as phones, larger screens, and foldables. The release of this feature will span many years; when fully implemented, the feature will allow users to preview the destination or other results of a return gesture before the completion of the gesture, so that the user can decide whether to continue to complete the gesture or Stay in current view.

insert image description here

Refer to the documentation to add support for predictive return gestures and run the official Codelab to find that it doesn't work on Vivo, OPPO, and Xiaomi, and it may be castrated. . . Using the emulator works fine. This feature is currently available for testing in the developer options. The official plan is to provide this interface to users in a future Android release.

Starting from Android 12L, we found that the official continues to provide optimization support on large-screen devices and foldable devices . It can be seen that the adaptation of large screens in the future is also a trend.

3. Language preference settings for each application

In many cases, multilingual users will have their system language set to one language (such as English), but want to select another language (such as Dutch, Chinese, or Hindi) for a particular application. To help apps provide a better experience for these users, Android 13 introduces the following features for apps that support multiple languages:

  • System Settings: Users can select their preferred language for each app in this centralized location.

    Your app must declare the attribute in your app's manifest android:localeConfigto tell the system that it supports multiple languages.

  • Other APIs: These public APIs, such as the and methods LocaleManagerin , allow apps to set a different language than the system language at runtime.setApplicationLocales()getApplicationLocales()

    These APIs are automatically synchronized with system settings; therefore, apps that use these APIs to create custom in-app language selectors will ensure users have a consistent user experience no matter where they select their language preference. The public API also helps reduce the amount of boilerplate code, supports split APKs, and supports automatic app backups to store user language settings at the app level.

Similarly, after trying several domestic mobile phones, this function was castrated, so I didn't try too much. For details, please refer to the document: Language preference settings for each application

4. Faster hyphenation

Hyphenation makes line-branched text easier to read and helps make interfaces more responsive. Starting with Android 13, hyphenation performance has been improved by up to 200%, so you can enable faster hyphenation in TextView with almost no impact on rendering performance. To enable faster hyphenation, setHyphenationFrequency()use fullFastor normalFastfrequency in .

Instructions:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    
    
    // 适用于聊天消息
    textView.setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_NORMAL_FAST);
    // 标准连词符
    textView.setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_FULL_FAST)
}

The following figure is fullFasta comparison before and after using attributes:

insert image description here


insert image description here

5. Themed App Icons

Starting with Android 13, you can choose to enable themed app icons. With this feature, users can adjust the color palette of supported Android app icons to inherit the color palette of selected wallpapers and other themes.

To support this feature, your app must provide an adaptive icon<adaptive-icon> and a monochrome app icon, and point to the monochrome app icon via a element in the manifest . If the user has themed app icons enabled (in other words, the themed icons toggle is turned on in the system settings), and the launcher supports this feature, the system will use the user's chosen wallpaper and theme to determine the tint color, That color will then be applied to the monochrome app icon.

insert image description here

The adaptation method is very simple, only need to add additional <monochrome/>monochrome application icon configuration to support this function.

<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
    <background android:drawable="@mipmap/ic_launcher_background"/>
    <foreground android:drawable="@mipmap/ic_launcher_foreground"/>
    <monochrome android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>

Several mobile phones tested do not support this function, so the emulator can only be used to test the effect. Simulator renderings:

insert image description here


There are so many adaptations about Android 13, and we still need to read the official documents for more changes. I also posted the link at the end of the article.

Finally, if this article is helpful to you, please like it. grateful!

reference

Guess you like

Origin blog.csdn.net/qq_17766199/article/details/130520330