Android 11 adaptation scheme change and adaptation strategy

Time:2022-5-8

Finally started the adaptation of Android 11. Record it for those who need it.

1. Preparatory work

The old rule is that we should firsttargetSdkVersionChange to 30. Maybe using compatibility debugging, which I will mention later.

2. Storage mechanism update

Scoped storage

The detailed adaptation method is not much different from that in the Android 10 adaptation strategy last year.

However, the need to pay attention is to usetargetSdkVersion >= 30, enforce the partitioned storage mechanism. BeforeAndroidManifest.xmlMedium increaseandroid:requestLegacyExternalStorage="true"The adaptation method has no effect.

Another change: Android 11 allows the use ofMediaStoreAPIs other than APIs directly visit media files in the shared storage space through file channels. This includes:

  • File API。
  • Native libraries, for examplefopen()

Assuming you haven’t adapted Android 10 before, this is good news for you. Android 10 inAndroidManifest.xmlMedium increaseandroid:requestLegacyExternalStorage="true"To adapt, it can be directly used on Android 11FileAPI access media files. I have to say, wait for the success of the party?

However, using the original file path to directly visit the media files in the shared storage space will be redirected toMediaStoreAPI, this redirection will have a functional impact (random reading and writing is about twice as slow). Moreover, the direct use of original documents is no better than the use ofMediaStoreAPI has more advantages, so the official strongly advocates direct useMediaStore API。

MANAGE_EXTERNAL_STORAGE

Of course, there is also a simple and rough adaptation method to obtain the permission of external storage. Suppose you use apps such as mobile housekeeper and document handler that need to visit a large number of documents and can begMANAGE_EXTERNAL_STORAGEAuthority, guide the user to the system setting page and open it. The code is as follows:

<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />

public static void checkStorageManagerPermission(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
!Environment.isExternalStorageManager()) {
Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}

The need to be careful is that even if you haveMANAGE_EXTERNAL_STORAGEPermission and no accessAndroid/data/Files in the directory.

aboutMANAGE_EXTERNAL_STORAGEAuthority, domestic use should have no impact. However, on Google play, we need to explain why we have itSAForMediaStoreIf it does not meet your application needs, it is allowed to be put on the shelf after review. Therefore, in general, I personally do not recommend you to directly ask for application in order to adapt to simplicityMANAGE_EXTERNAL_STORAGEjurisdiction.

See the document for other details: update of storage mechanism in Android 11.

Related API changes and application recommend Guo Lin’s article: new features of Android 11 and new tricks of scoped storage.

Storage access structure (SAF) changes

Android 11 adds the following constraints to saf:

  • applicationACTION_OPEN_DOCUMENT_TREEorACTION_OPEN_DOCUMENT, unable to readAndroid/data/andAndroid/obb/Directory and all its subdirectories.
  • applicationACTION_OPEN_DOCUMENT_TREEUnable to authorize access to storage root, download folder.

REQUEST_INSTALL_PACKAGES

In the adaptation of 8.0, we need to request the permission of “the equipment does not know the origin and use” before the equipment APK package. Generally speaking, the first time is to jump to the authorization page, let the user open it manually, and then come back to the app to check the device.

In Android 11, when the user opens the permission of “the device does not know the origin of use”, the app will be killed. This behavior is related to mandatory partitioned storage due to holdingREQUEST_INSTALL_PACKAGESThe use of authority can visit other usersAndroid/obbcatalogue

Fortunately, after the user publishes the permission, although the app will be killed, butThe device page will still pop up

Now I haven’t found a way to adapt this change. For details, see: Android 11 feature adjustment: external origin of the device and restart the app according to the application requirements

3. Permission change

Single authorization

Starting from Android 11, whenever the user requests permission related to location information, microphone or camera, the user oriented permission dialog box will include the option of only this time. Assuming that the user selects this option in the dialog box, the system will publish the temporary single authorization to the user.

The application of single permission authorization can visit relevant data within a period of time. The detailed time depends on the application behavior and user operation:

  • When the applied activity is visible, the application can visit relevant data.
  • It is assumed that the user can continue to visit relevant data in a short time by turning the application into background operation.
  • Suppose you claim a foreground service when the activity is visible, and the user then transfers your application to the background, then your application can continue to visit relevant data until the foreground service stops.
  • Assuming that the user revokes a single authorization (e.g. revoking in system settings), the application cannot access relevant data whether you advocate front-end service or not. As with any permission, if the user revokes the single authorization of the application, the application process will be suspended.

When the user opens the application next time and requests to visit the location information, microphone or camera for a function in use, the system will prompt the user to announce the permission again.

Assuming that you begged for relevant permissions before using permissions, this change has no impact on your use.

Request location authority

This part has been adjusted in Android 10, and the rules are as follows:

BegACCESS_FINE_LOCATIONorACCESS_COARSE_LOCATIONAuthority indicates that you have the authority to visit the equipment location information when you are at the front desk. In the request pop-up box, select “always allow” to indicate that the front and rear stations can obtain location information, and select “only allow in the process of application” to indicate that they have the authority of the front desk.

In Android 11, the option of “always allow” is cancelled in the request pop-up box. in other wordsAcquiesce in not publishing the location information of your background visiting equipment。 Hypothesis test requestACCESS_BACKGROUND_LOCATIONIf the authority requests any other authority together, the system will throw out an abnormality and will not announce any authority to the user.

The official adaptation claims and reasons are as follows:

It advocates the implementation of increasing requests for location authority, first asking for the access authority of front desk location information, and then asking for the access authority of back office location information. The implementation of successive requests can provide users with greater control and transparency, because they can better understand which functions in the application require access to background location information.

To sum up, two points can be drawn:

  • First ask for the front desk location information visit authority, and then ask for the back office location information visit authority.
  • Ask for the access authority of background location information alone, and do not ask for it together with other authorities.

We also need to pay attention to the performance of different policies and approaches on Android 11:

  • Application of Android 10 as the policy approach
    It is allowed to visit the location information permission of the front and background together, but there will be no “always allow” option.
  1. When there is no location information permission for front and background:

  1. When you have the location information permission of the front desk:

  • Application of Android 11 as the policy approach
  1. If you don’t have the location information permission of the front and background, you can only ask the location information permission of the front desk first:

  1. Have the location information permission of the front desk. When requesting the location information of the back desk, the system will jump to the following setting page.

Select “always allow” to indicate that you have access to front and back location information. If the user rejects two requests for location-based visits (directly come back, etc.), the subsequent requests for the same access will be directly prompted that the request fails. (here we need to guide users)

Here’s an explanation of “reject twice”, which is added on Android 11Visibility of permissions dialog boxIn the past, we clicked “no more inquiries” to reject authorization. Now it also includes going to the system settings like the above, and then clicking the back button is also regarded as rejecting authorization. Of course, if the user presses the back button to close the permission dialog box, this operation does not count.

To sum up, the difference with Android 10 is that it separates the request for background permission, increases the conditions for users to “reject”, and avoids the use of repeated requests for permission that users have rejected.

Package visibility

Package visibility is a new feature on Android 11 to improve the privacy and security of the system. Its effect is to restrict apps from obtaining information and device status of other apps at will. Avoid the use of virus software and spyware, which will lead to network fishing, leakage of user equipment information and other security matters.

Obtain the list of active visible applications and be able to implement instructionsadb shell dumpsys package queries, findforceQueryablepart. The following is the implementation effect of vivo iqoo mobile phone.

Queries:
system apps queryable: false
forceQueryable:
[com.android.BBKCrontab,com.vivo.fingerprint,com.vivo.epm,com.vivo.abe,com.vivo.fingerprintengineer,com.vivo.contentcatcher,com.vivo.floatingball,com.vivo.agent,com.vivo.nightpearl,android,com.wapi.wapicertmanage,com.vivo.vms,co
m.android.providers.settings,com.vivo.upslide,com.vivo.assistant,com.vivo.vivokaraoke,com.vivo.fingerprintui,com.android.wallpaperbackup,com.bbk.facewake,com.vivo.faceunlock,com.vivo.doubleinstance,com.vivo.audiofx,com.iqoo.powersav
ing,com.bbk.SuperPowerSave,com.vivo.vibrator4d,com.vivo.smartunlock,com.vivo.globalanimation,com.vivo.appfilter,com.vivo.voicewakeup,com.vivo.minscreen,com.android.bbklog,com.mobile.cos.iroaming,com.vivo.networkstate,com.vivo.daemon
Service,com.vivo.smartshot,com.vivo.vtouch,com.android.networkstack.tethering.inprocess,com.android.localtransport,com.vivo.pem,com.vivo.wifiengineermode,com.android.server.telecom,com.vivo.gamecube,com.vivo.aiengine,com.vivo.multin
lp,com.vivo.smartmultiwindow,com.vivo.permissionmanager,com.qti.diagservices,com.vivo.bsptest,com.qti.snapdragon.qdcm_ff,com.vivo.dr,com.vivo.sps,com.android.dynsystem,com.vivo.setupwizard,com.vivo.gamewatch,com.android.keychain,com
.vivo.faceui,com.android.networkstack.inprocess,com.android.location.fused,com.android.inputdevices,com.android.settings,com.iqoo.engineermode,com.vivo.fuelsummary]
[com.qualcomm.uimremoteserver,com.vivo.devicereg,com.qti.qualcomm.deviceinfo,com.volte.config,com.android.mms.service,com.android.ons,com.qualcomm.qcrilmsgtunnel,com.vivo.sim.contacts,com.qualcomm.qti.uimGbaApp,com.qualcomm.qti.
modemtestmode,com.android.stk,com.android.vendors.bridge.softsim,com.qualcomm.uimremoteclient,com.qti.qualcomm.datastatusnotification,com.qualcomm.qti.uim,com.android.phone,com.qualcomm.qti.dynamicddsservice,com.qualcomm.qti.telepho
nyservice,com.android.cellbroadcastservice,com.android.providers.telephony,com.qti.dpmserviceapp,com.android.incallui]
[com.android.vivo.tws.vivotws,com.android.bluetooth]
com.android.nfc
com.android.se
com.android.networkstack.permissionconfig
com.android.shell
com.android.providers.media.module
com.android.wifi.resources.overlay.common
com.android.theme.icon_pack.filled.themepicker
com.android.theme.icon_pack.circular.themepicker
com.android.server.telecom.overlay.common
......

It can be seen that all are system application package names, so our three-party application acquiescence is not visible. This change has more impact on the function of interaction between shared payment and other applications. Here is a brief example:


private static boolean hasActivity(Context context, Intent intent) {
PackageManager packageManager = context.getPackageManager();
return packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0;
}
public void test() {
Intent intent = new Intent();
intent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
Log.d("hasActivity:", hasActivity(this, intent) + "");
}

hasActivityProcess in the methodqueryIntentActivitiesTo determine whether this page exists. But intargetSdkVersion >= 30The acquiescence of these three parties is invisible. So they all come back false. Similar approachgetInstalledPackagesgetPackageInfoThey are also bound accordingly.

The solution is simple, inAndroidManifest.xmlMedium increasequeriesElement, in which the application package name with visible requirements is added.

<manifest package="com.example.app">
<queries>
<package android:name="com.tencent.mm" /&gt; <-  Specify wechat package name
</queries>
...
</manifest>

I also use the following package names in the adaptation. We can add them as needed:

<queries>
<!--  Microblog -- >
<package android:name="com.sina.weibo" />
<!-- QQ -->
<package android:name="com.tencent.mobileqq" />
<!--  Alipay --&gt;
<package android:name="com.eg.android.AlipayGphone" />
<!-- AlipayHK -->
<package android:name="hk.alipay.wallet" />
</queries>

In addition to the method of directly adding package names, we can add them according to intent and provider:

<manifest package="com.example.app">
&lt;queries>
<intent>
<action android:name="android.intent.action.SEND" />
<data android:mimeType="image/jpeg" />
</intent&gt;
<provider android:authorities="com.example.settings.files" />
</queries>
...
</manifest>

For detailed rules, see: handling software package visibility

Of course, there is also a simple and crude way to directly request authorityQUERY_ALL_PACKAGES。 Suppose your application needs are on the shelfGoogle Play, then perhaps we should pay attention to the relevant policies. In order to respect users’ privacy, we advocate that our application should be adapted according to the minimum package visibility required for normal operation.

There is a need to explain that we use it every daystartActivityThe method is not affected by the visibility behavior of the system software package, even ifhasActivityIf it is false, you can jump. Suppose we do a similar test before we jumphasActivityThe discrimination will be affected.

The final thing to watch out for is, usequeriesElement requirementsAndroid GradleThe plug-in version is4.1 and above, a merge occurred because other plug-ins in older versions were not compatible with this elementmanifestYour fault.

Front desk service type

In Android 10, in the front desk service, visit the location information, and the demand is in the correspondingserviceMedium increaselocationService type.

Similarly, in Android 11, when visiting the camera or microphone in the front desk service, the demand is in the correspondingserviceMedium increasecameraormicrophoneService type.

<manifest>
...
<service
android:name="MyService"
android:foregroundServiceType="microphone|camera" /&gt;
</manifest>

This binding change makes it impossible for the program to call the camera and microphone in the background. If you need to use it, you can only open the front desk service. Unless:

  • Services are claimed by system components.
  • A service is a claim made through the use of widgets.
  • Service is claimed through interaction with notification.
  • Service isPendingIntentYes, it was sent from another visible application.
  • The service is claimed by an application, which is a DPC and operates in the form of all equipment.
  • Services are provided by oneVoiceInteractionServiceApplication proposition of.
  • The service consists of aSTART_ACTIVITIES_FROM_BACKGROUNDClaims on the use of authority.

Active reset of permissions

Assuming that the application takes Android 11 or higher as the policy and approach, and has not been used for several months, the system will actively reset the active permissions of the user’s published operation to protect the user’s data. As shown in the figure below:

Note that there is a switch advocating active reset in the figure above. Assuming that our application has special needs, we can guide users to close it. The example code is as follows:

public void checkAutoRevokePermission(Context context) {
//Judge whether to open
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
!context.getPackageManager().isAutoRevokeWhitelisted()) {
//Jump to settings page    
Intent intent = new Intent(Intent.ACTION_AUTO_REVOKE_PERMISSIONS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.fromParts("package", context.getPackageName(), null));
context.startActivity(intent);
}
}

SYSTEM_ ALERT_ Windows permission

I didn’t use this part in the adaptation. I copied the document directly:

In Android 11, the system will announce to certain types of applications according to the request ideaSYSTEM_ALERT_WINDOWjurisdiction:

  • The system will have ideas toROLE_CALL_SCREENINGAnd beggedSYSTEM_ALERT_WINDOWFull use of this authority. Assumed loss of useROLE_CALL_SCREENING, the permission will be lost.

  • The system will passMediaProjectionIntercept the screen and begSYSTEM_ALERT_WINDOWUse and publish the permission in full unless the user has clearly declined to publish the permission to the user. When you use abort to intercept the screen, you will lose this permission. This use case is mainly used for live game broadcasting.

These applications do not need to be sentACTION_MANAGE_OVERLAY_PERMISSIONTo getSYSTEM_ALERT_WINDOWPermission, they just need to ask directlySYSTEM_ALERT_WINDOWJust.

MANAGE_OVERLAY_PERMISSIONIntent will always move the user to the system permission screen

Starting with Android 11,ACTION_MANAGE_OVERLAY_PERMISSIONIntent always takes users to the top-level settings screen, during which users can publish or revoke the applicationSYSTEM_ALERT_WINDOWjurisdiction. Any in intentpackage:Data will be ignored.

In earlier versions of other Android,ACTION_MANAGE_OVERLAY_PERMISSIONIntent can specify a software package, which will turn the user to the use of a dedicated screen to handle permissions. Starting from Android 11, this function will no longer be supported, but it is necessary for users to choose which permissions to publish or revoke. This change can make the publication of permissions more purposeful, and then achieve the purpose of protecting users.

Read mobile phone number

Suppose you’ve been throughTelecomManagerofgetLine1NumberMethod, orTelephonyManagerofgetMsisdnMethod to get the phone number. Then the demand increases in Android 11READ_PHONE_NUMBERSjurisdiction. The use of other methods is not limited.

<manifest>
<!--  Assuming that the permission is only used in Android 10 and lower, maxsdkversion = "29" -- >
<uses-permission android:name="android.permission.READ_PHONE_STATE"
android:maxSdkVersion="29" />
<uses-permission android:name="android.permission.READ_PHONE_NUMBERS" /&gt;
</manifest>

4. Other behavior changes

Custom view toast

Android 11For the application of the policy approach, the toast audio system that sends a custom view from the background will be shielded.The use of front desk will not be affectedToastCorrespondingsetViewandgetViewIt is also not advocated to use.

If you want to use it in the background, it is recommended to use the tacit toast orSnackbarreplace.

Apk signature

Android 11For the application of policy approaches, only the application of V1 signature cannot be used inAndroid 11Device or update on your device. It is necessary to sign with V2 or higher edition.

togetherAndroid 11Support for APK signature scheme V4 is added.

AsyncTask

AsyncTaskIn Android 11, it is no longer advocated to use, but to migrate to kotlin.

in additionHandlerUnspecifiedLooperThe structural approach is no longer advocated.

Advocate clear designationLooper

private Handler handler = new Handler(Looper.myLooper());
//Or
private Handler handler = new Handler(Looper.getMainLooper());

5. New things

Compatibility debugging things

In the past, when we did adaptation, we needed to first integrate the information in our projecttargetSdkVersionChange to the corresponding edition. This may cause you to be affected by other changes in the adaptation process, and this new compatibility debugging thing can make you not promotetargetSdkVersionOpen the adapter one by one for each change.

Application method:

  • Find the use compatibility change option in the developer options.
  • Click enter to find the application you need to debug
  • In the change list, find the change you want to open or close, and then click the corresponding switch.

Top line of the listDEFAULT_SCOPED_STORAGEIs to enable partition storage. For the detailed meaning of these constants, see the Android 11 change list.

For the detailed application methods of compatibility debugging, see: compatibility structure. I won’t open it here due to space limitation.

Wireless debugging

A wireless debugging function has been added to the developer option of Android 11. Similar to the function of connecting Bluetooth headset, it can carry out daily development and debugging without USB connection. (different from the previous Android WiFi ADB, this is true wireless, ha ha)

Application method:

  • Find wireless debugging in the developer options and open it.
  • For initial pairing, click “pairing device with pairing code”
  • taskadb pair ipaddr:portThen enter the pairing code for connection.

Precautions:

  • Stick to computers and mobile phones in one network.
  • Platform tools version must be greater than 30.0. Availableadb --versionCheck.

However, I understand that the connection is not very stable. I don’t know whether it is the problem of as or the problem of mobile phone. After locking the screen together, the connection will be disconnected, which is not well understood… Wait for the subsequent optimization.


This article is a little too much. To sum up, Android 11 has many changes in permissions, but assuming that you always abide by the best practices related to requesting permissions, you don’t need rated adaptation operations at all.

Finally, let’s focus onSingle authorization, visibility of permission dialog box, system_ ALERT_ Windows permission, device apkThese changes will work as long as they are on Android 11, whether you adapt to Android 11 or not. As for other changes and APIs (camera, 5g, waterfall screen, keyboard, etc.), I haven’t encountered them yet, so I haven’t listed them. If necessary, you can click the official document link at the end of the document to check.

As of the time of posting this blog, I only found BiliBili on my mobile phone. Bili is now compatible with Android 11. Most stay at 28, 29, and even 26 (the minimum adaptation standard for Android 8.0 on domestic shelves).