AndroidR Compatibility Adaptation Guide

AndroidR

android11.png

Android 11Builds on Androidearlier versions, adding several features and updates to keep users safe and improve transparency and control. All developers should review privacy features and test their apps. The exact impact may vary based on each app's core functionality, target platform, and other factors.

Introduction to Android 11

Privacy changes in Android 11

Android 11 behavior changes

Behavior changes for apps targeting Android 11

Material Privacy Changes

The table below summarizes the major privacy-related changes Android 11in .

Privacy Changes Affected apps caching strategy
Enforce partitioned storage
Apps that target Android 11 or higher will always be affected by partitioned storage behavior
Apps that target Android 11 or higher, requestLegacyExternalStorageand trueapps that target Android 10 without setting to to disable partitioned storage Update your app to use partitioned storage
Learn more about partitioned storage changes
One-time authorization
With the one-time authorization feature, users can grant temporary access to location, microphone, and camera
Apps running on Android 11 or higher that request location, microphone, or camera permissions Before attempting to access data protected by a permission, check that your app has the permission
Follow best practices for requesting permissions
Automatically reset permissions
The system automatically resets sensitive permissions on apps if the user has not interacted with the app for several months on Android 11 or higher
Apps that target Android 11 or higher and do most of their work in the background Ask users for permission to prevent the system from resetting appsLearn
more about automatic reset permissions
Background location access
Android 11 changes how users grant background location permissions to apps
Apps that target Android 11 or higher and require background location access Request permission to access location information in the foreground (coarse or fine) and in the background incrementally through multiple separate calls to the permission request method. If necessary, describe the benefits the user would gain from granting the permissionLearn
more about background location permissions in Android 11
Bundle visibility
Android 11 changes how apps query and interact with other installed apps on the same device
Apps that target Android 11 or higher and interact with other installed apps on the device <queries>Add a element to your app's manifestLearn
more about package visibility
Foreground service
Android 11 changes the way foreground services access location information, camera and microphone related data
Apps running on Android 11 or higher that access location, camera, or microphone in a foreground service For foreground services that need to access the camera and microphone, declare cameraand microphoneforeground service types. Note, however, that foreground services started while an app is in the background typically do not have access to location, camera, or microphone.
Learn more about changes to front desk services

Storage Mechanism Updates in Android 11

Android 11 (API level 30) further enhances the platform capabilities, providing better protection for application and user data on external storage devices. This release introduces several enhancements, such as an opt-in access mechanism for media raw file paths, batch edit operations for media, and interface updates to the storage access framework.

Android 11 Storage FAQ

Enforce Partitioned Storage

Apps running on Android 11 but targeting Android 10 (API level 29) can still request requestLegacyExternalStoragethe attribute . Apps can use this flag to temporarily disable changes related to partitioned storage , such as granting access to different directories and different types of media files.

When you update your app to target Android 11, the requestLegacyExternalStoragetag .

If it is an overlay installation, you can increase it android:preserveLegacyExternalStorage="true"and temporarily close the partition storage so that the developer can complete the data migration. Why is it temporary? Because as long as you uninstall and reinstall , it will be invalid.

Manage device storage

Starting with Android 11, apps using the partitioned storage model can only access their own app-specific cache files. If your app needs to manage device storage, follow the instructions on how to query available space .

  1. ACTION_MANAGE_STORAGECheck for free space by calling the intent action.
  2. Prompt the user to allow your app to clear all cache if there is insufficient free space on the device. To do this, call ACTION_CLEAR_APP_CACHEthe intent action.

Note : ACTION_CLEAR_APP_CACHEIntent actions can significantly impact device battery life and may remove large numbers of files from the device.

App-specific directories on external storage

Starting with Android 11, apps cannot create their own app-specific directories on external storage . To access the system-provided catalog for your app, call getExternalFilesDirs().

Media File Access

To allow easier access to media while maintaining user privacy, Android 11 adds the following features.

perform bulk operations

In Android 11 and higher, you can ask the user to select a set of media files and then update those media files in one operation. These methods provide better consistency across devices and allow users to more easily manage their media collections.

  • createWriteRequest(): A request from the user to grant the application write access to the specified group of media files.
  • createFavoriteRequest(): A request by the user to mark a specified media file on the device as a "favorite". Any app that has read access to the file can see that the user has marked the file as a favorite.
  • createTrashRequest(): A request from the user to place the specified media file in the device's trash. The contents of the Trash are permanently deleted after a system-defined period of time.
  • createDeleteRequest(): A request by the user to immediately and permanently delete the specified media file without placing it in the trash first.

After calling any of the above methods, the system will construct an PendingIntentobject . After the application invokes this intent, the user will see a dialog box requesting the user's consent for the application to update or delete the specified media file.

For example, here's how to build createWriteRequest()a call :

val urisToModify = /* A collection of content URIs to modify. */
val editPendingIntent = MediaStore.createWriteRequest(contentResolver,
        urisToModify)
// Launch a system prompt requesting user permission for the operation.
startIntentSenderForResult(editPendingIntent.intentSender, EDIT_REQUEST_CODE,
    null, 0, 0, 0)

Evaluate user responses. If the user provided a statement of consent, proceed to the media action. Otherwise, explain to the user why your app needs the permission:

override fun onActivityResult(requestCode: Int, resultCode: Int,
                 data: Intent?) {
    
    
    ...
    when (requestCode) {
    
    
        EDIT_REQUEST_CODE ->
            if (resultCode == Activity.RESULT_OK) {
    
    
                /* Edit request granted; proceed. */
            } else {
    
    
                /* Edit request not granted; explain to the user. */
            }
    }
}

You can use the same general pattern for createFavoriteRequest(), andcreateTrashRequest() .createDeleteRequest()

Access files using direct file paths and native libraries

https://developer.android.com/training/data-storage/shared/media#direct-file-paths

To help your app use third-party media libraries more smoothly, Android 11 (API level 30) and higher allows you to use MediaStoreAPIs other than APIs to access media files in shared storage. However, you can instead use any of the following APIs to access media files directly:

  • File API。
  • Native libraries, eg fopen().

Seeing this may cause doubts, Android10isn’t it stored in partitions, so that Android11it can be accessed directly using the file path again. In fact, here is Google’s optimization of the partitioned storage for developers (PS: I saw some developers’ feedback on the Internet that when the Uri of the partitioned storage is transferred to the Native layer, the Uri cannot be opened in the Native layer_ ) .

Some friends may ask that since media files Android11can be accessed directly File API, is partition storage still necessary? (PS: I know it must be necessary, but I wonder why it is necessary?)

testRequestPermissionActivityResult = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
    
    
    if (!it) {
    
    
        Log.d(TAG, "testRequestPermissionActivityResult:授权失败")
        return@registerForActivityResult
    }
    //val str = "/sdcard/DCIM/Camera/PXL_20221109_112534451.mp4"//可访问
    //val str = "/sdcard/screen/screen_10_23_17-41-47.png"//可访问
    //val str = "/sdcard/Download/charles-proxy-ssl-proxying-certificate.pem.crt"//不可访问
    //val str = "/sdcard/coverage.ec"//不可访问
    //val str = Environment.getExternalStoragePublicDirectory("").absolutePath + "/test.txt"//不可访问
    //val str = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath + "/tanzhenxing.txt"//不可访问
    //val str = Environment.getExternalStorageDirectory().absolutePath+"/Download/tanzhenxing.txt"//不可访问
    val str = "/sdcard/Download/tanzhenxing02.txt"//不可访问
    //val str = "/sdcard/Download/PXL_20221116_120102566.jpg"//可访问
    //如果您没有任何与存储空间相关的权限,您可以访问应用专属目录中的文件,并可使用 File API 访问归因于您的应用的媒体文件。
    //如果您的应用尝试使用 File API 访问文件但没有必要的权限,就会发生 FileNotFoundException。
    //PS:如果这个文件是自己应用程序创建的,是可以通过FileAPI进行访问的,但卸载重装会丢失访问权限;如果没有访问权限会发生异常;
    val file = File(str)
    if (!file.exists()) {
    
    
        file.createNewFile()
    }
    setFileContent(file, "\nHello World~!")//给文件写入内容
    Log.d(TAG, "fileName:" + file.name)
    Log.d(TAG, "fileName:" + file.totalSpace)
    Log.d(TAG, "fileName:" + getFileContent(file))//输出文件内容
}
binding.test.setOnClickListener {
    
    
    testRequestPermissionActivityResult.launch(android.Manifest.permission.READ_EXTERNAL_STORAGE)
}

We look at the piece of code above and know that if it is adapted Android11, we can only File APIaccess media files and files that we have access to through ; in addition, if we access other files, it will cause the following crash:

Caused by: java.io.FileNotFoundException: /sdcard/Download/tanzhenxing.txt: open failed: EACCES (Permission denied)
	at libcore.io.IoBridge.open(IoBridge.java:574)
	at java.io.FileInputStream.<init>(FileInputStream.java:160)
	at com.tzx.androidr.AndroidRMainActivity.getFileContent(AndroidRMainActivity.kt:57)
	at com.tzx.androidr.AndroidRMainActivity.onCreate$lambda-0(AndroidRMainActivity.kt:41)
	at com.tzx.androidr.AndroidRMainActivity.$r8$lambda$MxKbezjb4Znij4KrMlxgA5nFBbM(Unknown Source:0)
	at com.tzx.androidr.AndroidRMainActivity$$ExternalSyntheticLambda1.onActivityResult(Unknown Source:4)
	at androidx.activity.result.ActivityResultRegistry.doDispatch(ActivityResultRegistry.java:392)
	at androidx.activity.result.ActivityResultRegistry.dispatchResult(ActivityResultRegistry.java:351)
	at androidx.activity.ComponentActivity.onRequestPermissionsResult(ComponentActivity.java:667)
	at androidx.fragment.app.FragmentActivity.onRequestPermissionsResult(FragmentActivity.java:636)
	at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:8759)
	at android.app.Activity.dispatchActivityResult(Activity.java:8617)
	at android.app.ActivityThread.deliverResults(ActivityThread.java:5340)
	... 13 more

What method do I need to use to access files after adaptation Android11?

Access to the app-specific catalog

//分区存储空间,/data/data/package/files
val file = File(context.filesDir, filename)
//应用专属外部存储空间,/storage/sdcard0/Android/data/package/files
val appSpecificExternalDir = File(context.getExternalFilesDir(), filename)

Access public media directory files

Use MediaStore or SAF (Storage Access Framework – Storage Access Framework) ;

Access data in other apps

To protect user privacy, on devices running Android 11 or higher, the system will further restrict your app's access to other apps' private directories.

Access the data directory on the internal storage device

If your app targets Android 11, you cannot access files in any other app's data directory, even if the other app targets Android 8.1 (API level 27) or lower and has made its data directory The same is true for files that are world-readable.

Access application-specific directories on external storage

On Android 11, apps can no longer access files in any other app's app-specific directories on external storage.

All file access

An app can request "All Files Access" from the user by doing the following:

  1. Declare MANAGE_EXTERNAL_STORAGEpermissions .
  2. Use ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSIONthe intent action to direct the user to a system settings page where they can enable the following option for your app: Grant administrative permissions to all files .

To determine whether your app has been granted MANAGE_EXTERNAL_STORAGEthe permission ,

Please call Environment.isExternalStorageManager().

<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
val intent = Intent()
intent.action= Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION
startActivity(intent)
val isHasStoragePermission= Environment.isExternalStorageManager()

Document Access Restrictions

To allow developers time to test, the following Storage Access Framework (SAF)-related changes will only take effect when apps target Android 11 or higher.

access directory

ACTION_OPEN_DOCUMENT_TREEYou can no longer request access to the following directories using intent actions:

  • The root directory of the internal storage volume.
  • The root directory of each SD card volume that the device manufacturer considers reliable, whether the card is emulated or removable. A reliable volume is one that an application can successfully access most of the time.
  • DownloadTable of contents.

access files

You can no longer use ACTION_OPEN_DOCUMENT_TREEthe or ACTION_OPEN_DOCUMENTintent action to request the user to select individual files from the following directories:

  • Android/data/directory and all its subdirectories.
  • Android/obb/directory and all its subdirectories.

Permission Application Related Changes

single authorization

Starting with Android 11, whenever an app requests permissions related to location, microphone, or camera, the user-facing permissions dialog includes an option Only this time . If the user selects this option in the dialog, the system grants the app a temporary one-time authorization.

The app can then access the relevant data for a period of time, depending on the app's behavior and the user's actions:

  • When the application's activity is visible, the application can access related data.
  • If the user puts the app in the background, the app can continue to access relevant data for a short period of time.
  • If you start a foreground service while the activity is visible, and the user then backgrounds your app, your app can continue to access related data until the foreground service stops.

onetimeprompt.png

App process terminates when permission is revoked

If the user revokes a single authorization (for example, in the system settings), the app cannot access the relevant data, regardless of whether you have started the foreground service. As with any permission, if the user revokes the app's one-time authorization, the app process will be terminated.

The next time the user opens the app and a feature in the app requests access to location, microphone, or camera, the user will be prompted again for permission.

Automatically reset permissions for unused apps

If an app targets Android 11 or higher and has not been used in a few months, the system protects user data by automatically resetting runtime-sensitive permissions that the user has granted to the app. This has the same effect as a user viewing permissions in system settings and changing the app's access level to deny . If your app follows best practices for requesting permissions at runtime , you don't need to make any changes to your app. This is because when a user interacts with a feature in your app, you should verify that the feature in question has the required permissions.

Visibility of permission dialog

Starting with Android 11, after the app is installed on the device, if the user taps Deny for a specific permission multiple times while using the app , the user will not see the system permission when your app requests that permission again dialog box. This action indicates that the user wishes to "don't ask again". In previous releases, users saw the system permission dialog whenever your app requested permission, unless the user had previously checked the "Don't ask again" dialog or option. This behavior change in Android 11 is intended to avoid repeatedly requesting permissions that the user has chosen to deny.

System notification window changes

In Android 11, there have been some changes to how SYSTEM_ALERT_WINDOWpermissions . These changes can make the granting of permissions more purposeful, so as to achieve the purpose of protecting users.

Automatically grant SYSTEM_ALERT_WINDOW permission to certain apps upon request

Certain types of apps are automatically granted SYSTEM_ALERT_WINDOWpermissions :

  • This permission is ROLE_CALL_SCREENINGautomatically SYSTEM_ALERT_WINDOWgranted to any app that has and requests . If the app is lost ROLE_CALL_SCREENING, the permission is lost.
  • This permission is MediaProjectionautomatically SYSTEM_ALERT_WINDOWgranted to all apps that request via the screenshot unless the user has explicitly denied the permission to the app. This permission is lost when the app stops capturing the screen. This use case is mainly for game streaming applications.

These apps don't need to send ACTION_MANAGE_OVERLAY_PERMISSIONfor SYSTEM_ALERT_WINDOWthe permission, they SYSTEM_ALERT_WINDOWcan .

MANAGE_OVERLAY_PERMISSION intent will always take the user to the system permissions screen

Starting with Android 11, ACTION_MANAGE_OVERLAY_PERMISSIONintents always take the user to the top-level settings screen, where the user can grant or revoke SYSTEM_ALERT_WINDOWpermissions . Any package:data is ignored.

In earlier versions of Android, ACTION_MANAGE_OVERLAY_PERMISSIONthe intent could specify a package that would take the user to an app-specific screen to manage permissions. Starting with Android 11, this feature will no longer be supported, instead the user must first choose which apps to grant or revoke permissions for. This change can make the granting of permissions more purposeful, so as to achieve the purpose of protecting users.

telephone number

Android 11 changes the telephony-related permissions your app uses to read phone numbers.

If your app targets Android 11 or higher and needs to access the phone number APIs shown in the list below, you must request READ_PHONE_NUMBERSthe permission instead of READ_PHONE_STATEthe permission.

If your app declares READ_PHONE_STATEto call methods other than those in the preceding list, you can continue to request it in all Android versions READ_PHONE_STATE. However, if you only use READ_PHONE_STATEpermissions , update your manifest file as follows:

  1. READ_PHONE_STATEChange the declaration for so that your app only uses the permission on Android 10 (API level 29) and lower.
  2. Add READ_PHONE_NUMBERSpermissions .

The following manifest declaration snippet demonstrates this process:

<manifest>
    <!-- Grants the READ_PHONE_STATE permission only on devices that run
         Android 10 (API level 29) and lower. -->
    <uses-permission android:name="READ_PHONE_STATE"
                     android:maxSdkVersion="29" />
    <uses-permission android:name="READ_PHONE_NUMBERS" />
</manifest>

Updates to message boxes

Custom message boxes from the background are blocked

For security reasons, and to maintain a good user experience, message boxes containing custom views are blocked if they are sent from the background by apps targeting Android 11 or higher. Note that text message boxes are still allowed; such message boxes are Toast.makeText()created and not called setView().

If your app still tries to post a message box containing a custom view from the background, instead of displaying an appropriate message to the user, the following message is logged in logcat:

W/NotificationService: Blocking custom toast from package \
  <package> due to package not in the foreground

The concern is if the app is in the background and needs to show toast. Then use native Toast~!

message box callback

If you want to be notified when a message box (text message box or custom message box) appears or disappears, use addCallback()the method .

camera

The media intent operation requires the system default camera

Starting from Android 11, only the pre-installed system camera application can respond to the following intent operations:

If multiple pre-installed system camera apps are available, the system displays a dialog for the user to select an app. If you want your app to use a specific third-party camera app to capture pictures or video on its behalf, you can make those intents explicit by setting a package name or component for the intent.

App packaging and installation

compressed resource file

Apps targeting Android 11 (API level 30) or higher will fail to install if they contain a compressed resources.arscfile or if the file is not aligned on a 4-byte boundary. If any of these conditions exist, the system will not be able to memory map this file. Resource tables that cannot be memory mapped must be read into a buffer in RAM, putting unnecessary memory pressure on the system and greatly increasing the device's RAM usage.

APK Signature Scheme v2 is now required

Apps targeting Android 11 (API level 30) that are currently only signed with APK Signature Scheme v1 must now also be signed with APK Signature Scheme v2 or higher. Users cannot install or update apps signed only with APK Signature Scheme v1 on devices running Android 11.

To verify that your app is signed with APK Signature Scheme v2 or higher, you can use Android Studio or apksignerthe tool from the command line .

Note: To support devices running older versions of Android, you should continue to sign your APKs with APK Signature Scheme v1 in addition to signing your APKs with APK Signature Scheme v2 or higher.

Access to background location information

Android 11 changes how features in apps gain access to background location information . This section describes each of the above changes.

If a feature in your app accesses location information from the background, verify that such access is necessary and consider other ways to obtain the information the feature needs. For more information about accessing location in the background, see Accessing location in the background page.

A separate request to access location information in the background

As described in the guide on how to request location access at runtime , you should perform incremental location requests. This best practice is enforced if your app targets Android 11 or higher. If you request both foreground location permission and background location permission, the request is ignored and neither permission is granted to your app .

Changes to the permissions dialog

On devices running Android 11 or higher, when a feature in your app requests background location access, the system dialog does not include a button to enable background location access permission. To enable background location access, the user must set the Always Allow option for the app's location permissions on the settings page , as described in the guide on how to request background location access .

Background location information access permission usage summary

The above three parts are excerpted from the location information update in Android 11. After reading it, do you feel in the fog? Here are a few examples for everyone to understand.

private fun initTestLocationFunc() {
    
    
    binding.testLocation.setOnClickListener {
    
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    
    
            requestPermissions(arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_BACKGROUND_LOCATION), 100)
        }
    }
}

android11以下的设备, apply for foreground and background location permissions (any targetSdkVersion):

android910requestlocation.png

Android11及以上的设备, targetSdkVersion<=29 (Android 10), apply for foreground and background location permissions:

android11requestloctiondevice11.png

Android11及以上的设备, targetSdkVersion=30 (Android 11), apply for foreground and background location permissions:

No response , (PS: Android 11 or higher is the target platform, the system enforces this best practice. If you request both foreground location access and background location access permission, the request will be ignored , and does not grant either of these permissions to your app. A separate request for background location access )

private fun initTestForeGroundLocationFunc() {
    
    
    binding.testForegroundLocation.setOnClickListener {
    
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    
    
            requestPermissions(arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), 100)
        }
    }
}
private fun initTestBackGroundLocationFunc() {
    
    
    binding.testBackgroundLocation.setOnClickListener {
    
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    
    
            requestPermissions(arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION), 100)
        }
    }
}

Android11及以上设备, first apply for the foreground location permission, and then apply for the background location permission:

  • Execute the application for foreground permission first (targetSdkVersion does not distinguish);

android11requestforebackgrounddevice11.png

  • Then execute the application background permission (targetSdkVersion=29);

android10requestbackgrounddevice11.png

  • Then execute the application background permission (targetSdkVersion=30);

android11requestbackgrounddevice11.png

After reading the above implementation results, we clearly know how to apply for background location permissions.

  • targetSdkVersion<30In some cases, if you have judged the location permissions of the foreground and background before, then there is no need to worry, there is nothing to adapt.

  • targetSdkVersion>30In some cases, it is necessary to separately apply for the front-end and back-end location permissions, and explain and guide the background location permission application, of course, to better serve users.

Package Visibility

Package visibility in Android 11

Android 11 changes the way apps query and interact with other apps a user has installed on the device. Using <queries>the element , an app can define a set of other packages that it can access. This element helps encourage the principle of least privilege by telling the system which other packages should be exposed to your app. Additionally, this element helps app stores such as Google Play evaluate the privacy and security an app provides to users.

Declare that your app interacts with a specific set of other apps

If your app targets Android 11 or higher, you might need to add <queries>a element . In <queries>the element , specify additional applications by package name , by intent signature , or by provider authorization , as described in the following sections.

Query and interact with specific packages

If you know a specific set of apps that you want to query or interact with (for example, apps that integrate with your app or that you use as a service), add their package names to a set of elements inside <queries>the element <package>:

<manifest package="com.example.game">
    <queries>
        <package android:name="com.example.store" />
        <package android:name="com.example.services" />
    </queries>
    ...
</manifest>

Query and interact with an application given an intent filter

Your app may need to query or interact with a set of apps with a specific purpose, but you may not know the exact package name to add. In this case, you <queries>can list the intent filter signatures in the element . Your application can then discover applications with matching <intent-filter>elements .

The following example allows your app to see installed apps that support JPEG image sharing:

<manifest package="com.example.game">
    <queries>
        <intent>
            <action android:name="android.intent.action.SEND" />
            <data android:mimeType="image/jpeg" />
        </intent>
    </queries>
    ...
</manifest>

<intent>Elements have some restrictions, see https://developer.android.com/training/basics/intents/package-visibility#intent-signature for details.

All apps (not recommended)

In rare cases, your app might need to query or interact with all installed apps on the device, regardless of their components. To allow your app to see all other installed apps, the system provides QUERY_ALL_PACKAGESthe permission .

Here are some use cases for adding QUERY_ALL_PACKAGESpermissions :

  • Accessible apps
  • browser
  • Device Management App
  • security application
  • antivirus application

Typically, however, your app's use case can be achieved by interacting with a set of automatically visible apps and declaring in your manifest file which other apps your app needs to access. To respect user privacy, your app should request the minimum package visibility required for your app to function properly.

This policy update from Google Play provides guidelines for apps that require QUERY_ALL_PACKAGESthe permission .

API updates

5G

Add 5G capabilities to your app

When deciding how to interact with 5G, think about what kind of experience you're trying to create. 5G can enhance your application in a number of ways, including:

  • Automatically make current experiences faster and better thanks to 5G improvements in speed and latency.
  • Enhance user experience, such as by displaying 4k video or downloading higher resolution game assets.
  • After confirming that the increased data consumption will not cost the user, add experiences that are typically only available over Wi-Fi, such as unsolicited downloads that are generally reserved for unmetered Wi-Fi.
  • Deliver an experience unique to 5G that can only be achieved on high-speed, low-latency networks.

Android 11 adds 5G APIs that enable your apps to add a variety of advanced features.

Reception

In Android 11, there have been some changes to when foreground services can access the device's location, camera, and microphone. This helps protect sensitive user data.

Foreground service type camera and microphone

If your app targets Android 11 or higher and accesses the camera or microphone in a foreground service, you must add the foreground service type camera and microphone.

The previous article described that when adapting to Android 10, the foreground location service must be added android:foregroundServiceType="location".

Now two more permission restrictions (camera and microphone) have been added on Android11. If the foreground service needs to access the location, camera and microphone, please declare the service as shown in the following code snippet:

//AndroidManifest.xml
<manifest>
    ...
    <service ... android:foregroundServiceType="location|camera" />
</manifest>

Restrictions on access while in use

If your app starts a foreground service while running in the background , the foreground service cannot access the microphone or camera. Also, the service cannot access location information unless your app has permission to do so in the background .

For some exemption restrictions , you can refer to https://developer.android.com/guide/components/foreground-services#bg-access-restriction-exemptions.

Data Access Audit

In order to make the process of apps and their dependencies accessing users' private data more transparent, Android 11 introduces the data access audit function. With the insights from this process, you can better identify possible unintended data access. Your app can register AppOpsManager.OnOpNotedCallbackan instance that can take action each time any of the following events occur:

  • The app's code accesses private data. To help you determine which part of your app's logic invoked an event, you can audit data access by attribution tag.
  • Rely on code in a library or SDK to access private data.

For more information, see our guidance on how to audit access to data .

Briefly describe the use of this function and create a marked Context. Then when you use this Context to access some private data, you can get the relevant call information in the registered callback.

In fact, I feel that this is not very effective, and the cost of intrusion into the code is too high. We can easily handle the same function through facets.

FAQ

Android 11 storage FAQ Android 11 storage FAQ , I will find a few records from it.

Does Scoped Storage allow applications to access files using file paths, for example using the file API?

We recognize that some apps rely on code or libraries that directly access paths to media files. So on Android 11, an app with read external storage permission can access a file with a file path in the scoped storage environment. On Android 10 devices, this is not available to apps in scoped storage environments unless android:requestLegacyExternalStoragethey opt out by setting a manifest attribute. To ensure continuity across Android versions, you should also opt out if your app targets Android 10 or higher. For more information, see Partitioned Storage Best Practices .

How does file path access perform compared to the Media Store API?

Performance really depends on the exact use case. For sequential reads such as video playback, file path access provides comparable performance to media storage. But for random reads and writes, using a file path can be twice as slow. For the fastest and most consistent reads and writes, we recommend using Media Store API.

Are there any further restrictions on using Storage Access Framework in Android 11 compared to Android 10?

Apps targeting Android 11 (API level 30) and using the Storage Access Framework will no longer be able to grant access to directories, such as the SD card's root and downloads directories. Regardless of the target SDK, the Storage Access Framework on Android 11 cannot be used to gain access to Android/datathe and Android/obbdirectories . Learn more about these limits and ways to test the behavior.

Are applications in partitioned storage limited to writing files to their application-specific data directories?

In partitioned storage, applications can contribute media files to the Media Store collection. Media StoreFiles are placed into well-organized folders based on file type, such as DCIM, Movies, Downloads, and more. For all such files, applications can also continue to access them through the file API. The OS maintains a system to attribute applications to each media storage file, so applications can read/write the files they originally contributed to the media storage without storage permissions.

Media Store DATA column is deprecated, what are the usage guidelines?

On Android 10, apps in a scoped storage environment cannot access files using file paths. To be consistent with this design, we deprecated the DATA column at that time. Based on your feedback on your need to use existing native code or libraries, Android 11 now supports file path access for apps in partitioned storage. So DATA columns are actually useful for some situations. For media store inserts and updates, Scoped Storageapplications in should use DISPLAY_NAMEthe and RELATIVE_PATHcolumns. They can no longer use the DATA column for this. When reading a media store entry for a file that exists on disk, the DATA column will have a valid file path for use with the file API or NDK file libraries.

Summarize

The adaptation of Android 11 and Android 10 are best carried out together, because the impact of privacy changes related to these two versions on developers is mainly the business logic modification caused by the adaptation of partition storage.

Relevant adaptation of partition storage

  1. Android10You can use android:requestLegacyExternalStoragethe transition first, but during the transition, we need to migrate some data in the application to the relevant partition storage; after completing this step, it will be Android11easier for us to adapt;
  2. When performing Android11related partition storage adaptation, related media operations in the application can still be used after we authorize the storage permission File API. This basically solves most of the partition storage adaptation problems. When we Android10adapted, we migrated the relevant data files to the private space of the application, which can also be File APIaccessed through files.
  3. Finally! We just need to modify some photos, adaptation recordings, and image storage, as well as some external sharing services.

In addition, after many app compliance rectifications in foreign countries, most of our developers only need to focus on the modification of custom message boxes from the background , APK signature scheme V2 , background location information access rights , and phone numbers . For other Android 11 modifications , such as wireless debugging , device-to-device file transfer , restricting read access to the APN database , and declaring the usage of the "Accessibility" button in the metadata file , you can refer to Android 11 as the target platform. App behavior changes .

Reference article: Can't wait, Android 11 is really coming, here is the most complete adaptation practice guide

GitHub Demo

If you want to read more articles by the author, you can check out my personal blog and public account:
Revitalize Book City

Guess you like

Origin blog.csdn.net/stven_king/article/details/128429760