Talk about run-time permissions for Android 6.0

Source: Internet
Author: User

Talk about run-time permissions for Android 6.0
    • Permission fits
    • Cotton Candy Runtime permissions
    • Grouping of permissions
    • Normal permissions
      • Normal Permissions List
    • Special permissions
      • Request System_alert_window
      • Request Write_settings
    • Dangerous permissions
    • Do I have to support run-time permissions?
    • Does not support run-time permissions crash?
      • But a bit of a bad thing
    • It's got to come.
      • A standard process
      • How to apply in bulk
      • It's tiring to apply for so many privileges.
    • Precautions
      • API issues
      • Multi-system issues
    • Two permissions
    • A bit of advice
    • Attention

Android 6.0, code-named Marshmallow, since its inception, its main features run-time permissions are very concerned. This feature not only improves user experience with applications, but also enables application developers to make changes in their practice development.

Developers with no in-depth knowledge of runtime permissions often have a lot of questions, such as what is run-time permissions, which are run-time permissions, whether my app crashes on 6.0 systems, and how to support runtime permissions mechanisms. This article tries to answer some of these questions, hoping that the reader can find the perfect answer after the reading is done.

Permission fits

In 6.0 before the system, is the right to a knife-cut processing mode, as long as the user installation, manifest application permissions will be given, and after the installation of permissions can not be revoked .

In this case, when we install an app from Google Play, we get a permission prompt before installing it.

When the above dialog box pops up, the user has only two options:

    • I trust you, even with sensitive authority.
    • You a * * application, for this permission to do, I still do not install.

So, this one-size-fits-all approach still has drawbacks, and we have no way to allow only certain permissions or deny certain permissions.

Cotton Candy Runtime permissions

Starting with Marshmallow, the Android system introduces a new permission mechanism, the runtime permissions that this article will talk about.

What are run-time permissions? Take a chestnut, for example, for an application that needs to be photographed, when the runtime permissions are in effect, the camera permissions are not given after the installation, but are requested when the app is running (for example, when the user presses the camera button) to see the effect.

Next, the camera permissions are processed to the full discretion of the user. is not a bit like the processing of the Apple system, do not say that this is plagiarism, for the time being called the Master Yi Long Technology to the system of Yi.

Grouping of permissions

Android has a lot of permissions, but not all permissions are sensitive permissions, so the 6.0 system to classify the permissions, generally for the following categories

    • Normal Protection permissions
    • Dangerous (dangerous) permissions
    • Special (particular) permissions
    • Other permissions (typically rarely used)
Normal permissions

The normal permission has the following several characteristics

    • No significant impact on user privacy or security issues.
    • These permissions are granted after installation and do not require a user to display reminders, and users cannot cancel these permissions .
Normal Permissions List
ACCESS_location_extra_commandsaccess_network_stateaccess_notification_policyaccess_wifi_statebluetoothbluetooth_adminbroadcast_stickychange _network_statechange_wifi_multicast_statechange_wifi_statedisable_keyguardexpand_STATUS_BARGET_package_sizeinternetkill_background_processesmodify_audio_settingsnfcread_sync_settingsread _sync_statsreceive_boot_completedreorder_tasksrequest< Span class= "hljs-emphasis" >_install_packagesset_time_zoneset_wallpaperset_wallpaper_hintstransmit_iruse_fingerprintvibratewake_lockwrite_ Sync_settingsset_alarminstall_shortcutuninstall_shortcut        

The above-mentioned permissions are basically designed about the network, Bluetooth, time zone, shortcuts and so on, as long as the manifest specified these permissions, it will be granted, and cannot be revoked.

Special permissions

Here's a special privilege to talk about in advance, because it's relatively simple.

Special permissions, as the name implies, are some particularly sensitive permissions in Android systems, mainly by two

    • System_alert_window, set up a floating window to do some black tech
    • Write_settings Modifying system settings

With respect to the authorization of the above two special permissions, the practice is done using the startActivityForResult start authorization interface.

Request System_alert_window
private static final int REQUEST_CODE = 1;private  void requestAlertWindowPermission() {    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);    intent.setData(Uri.parse("package:" + getPackageName()));    startActivityForResult(intent, REQUEST_CODE);}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {    super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE) { if (Settings.canDrawOverlays(this)) { Log.i(LOGTAG, "onActivityResult granted"); } }}

The above code needs to be aware that

    • To Settings.ACTION_MANAGE_OVERLAY_PERMISSION start an implicit intent with an action
    • Use "package:" + getPackageName() the package name information that carries the app
    • Using Settings.canDrawOverlays methods to determine authorization results
Request Write_settings
private static final int REQUEST_CODE_WRITE_SETTINGS = 2;private void requestWriteSettings() {    Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);    intent.setData(Uri.parse("package:" + getPackageName()));    startActivityForResult(intent, REQUEST_CODE_WRITE_SETTINGS );}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_WRITE_SETTINGS) { if (Settings.System.canWrite(this)) { Log.i(LOGTAG, "onActivityResult write settings granted" ); } }}

The above code needs to be aware that

    • To Settings.ACTION_MANAGE_WRITE_SETTINGS start an implicit intent with an action
    • Use "package:" + getPackageName() the package name information that carries the app
    • Using Settings.System.canWrite methods to detect authorization results

Note: Application requests are generally not recommended for these two special permissions.

Dangerous permissions

Dangerous permissions are actually objects that are primarily handled by run-time permissions, which can cause privacy issues or affect other programs to run. Dangerous permissions in Android can be categorized into the following groups:

    • CALENDAR
    • CAMERA
    • CONTACTS
    • Location
    • Microphone
    • PHONE
    • Sensors
    • Sms
    • STORAGE

Each permission group and its specific permissions, you can refer to:

Do I have to support run-time permissions?

Currently the application can actually not need to support run-time permissions, but ultimately it must be supported, only a matter of time.

If you want to not support the runtime permissions mechanism is simple, just want to targetSdkVersion set less than 23 can be, meaning to tell the system, I have not fully in the API 23 (6.0) completely, do not give me to start a new feature.

Does not support run-time permissions crash?

Maybe, but not the kind of crack that's going on all the way up there.

If your app will be targetSdkVersion set below 23, then the run-time permission mechanism will not be turned on for this app on the 6.0 system, which is handled as a previous cut.

But a bit of a bad thing

6.0 system provides an application rights management interface, the interface is so long

Since it is manageable, the user can cancel the permission when an app that does not support run-time permissions is canceled

The system will pop up a dialog to remind you of the harm of revocation, if the user is determined to revoke, will bring the following reaction

    • If your program is running, it will be killed.
    • Crashes may occur when your app is running again

Why it could crash, like the code below

TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);String deviceId = telephonyManager.getDeviceId();if (deviceId.equals(mLastDeviceId)) {//This may cause NPE  //do something}

If the user revokes permission to get DeviceID, the DeviceID is null when run again, and crashes if the program is improperly processed.

It's got to come.

6.0 of the runtime permissions, we ultimately want to support, usually we need to use the following API

    • The int checkselfpermission (String permission) is used to detect whether the app already has permissions
    • void Requestpermissions (string[] permissions, int requestcode) to request single or multiple permissions
    • void Onrequestpermissionsresult (int requestcode, string[] permissions, int[] grantresults) callback after the user responds to the request

Take a request camera permission as an example

@Overridepublic void OnClick (View v) {if (! ( Checkselfpermission (Manifest.permission.CAMERA) = = packagemanager.permission_granted)) {Requestcamerapermission ();}}private static final int request_permission_camera_code = 1;private void Requestcamerapermission () { requestpermissions (new String[]{manifest.permission.camera}, Request_permission_camera_code); } @Override public void Onrequestpermissionsresult (int requestcode, string[] permissions, int[] Grantresults) { Super.onrequestpermissionsresult (requestcode, permissions, grantresults); if (Requestcode = = Request_permission_camera_code) { int grantresult = Grantresults[0]; Boolean granted = Grantresult = = Packagemana Ger. permission_granted; log.i (LogTag, "Onrequestpermissionsresult granted=" + granted);  } }

Usually, we get a dialog box like this

When the user chooses to allow, we can handle the response in the Onrequestpermissionsresult method, such as turning on the camera

when the user rejects, your app may start to be dangerous.

When we try to apply for permission again, the pop-up dialog is a bit different from the previous one, mainly in the form of a checkbox. Such as

When the user checked the "no longer ask" refusal, your program basically this permission on the game over.

However, you still have a glimmer of hope, that is, before the above dialog box to do some information, such as you use the purpose of this permission (be sure to confess).

Shouldshowrequestpermissionrationale This API can help us to determine whether the next dialog box contains a "Don't ask" selection box.

A standard process
if (!(checkSelfPermission(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED)) {  if (shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {      Toast.makeText(this, "Please grant the permission this time", Toast.LENGTH_LONG).show();    }    requestReadContactsPermission();} else {  Log.i(LOGTAG, "onClick granted");}
How to apply in bulk

The bulk request permission is simple and requires only a string array to place multiple permissions. such as request code

private static final int REQUEST_CODE = 1;private void requestMultiplePermissions() {    String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE};    requestPermissions(permissions, REQUEST_CODE);}

The corresponding interface effect is

Note: multiple permission requests with shorter intervals are suggested to be set to multiple permission requests in a single order, avoiding the appearance of multiple dialog boxes, resulting in less-than-good visual effects.

It's tiring to apply for so many privileges.

In fact, you don't need each permission to explicitly apply, for example, if your app grants permission to read a contact, then your app is given permission to write to the contact. Because both permissions for reading contacts and writing to contacts are grouped by contact permissions, other permissions for that group are allowed once a permission is allowed in the group.

Caveats API Issues

Since Checkselfpermission and Requestpermissions are added from API 23, less than version 23, they need to be judged at runtime or using the methods provided in the support Library v4

    • Contextcompat.checkselfpermission
    • Activitycompat.requestpermissions
    • Activitycompat.shouldshowrequestpermissionrationale
Multi-system issues

When we support 6.0 must also support 4.4,5.0 these systems, so need in many cases, need to have two sets of processing. Like camera permissions.

if (isMarshmallow()) {    requestPermission();//然后在回调中处理} else {    useCamera();//低于6.0直接使用Camera}
Two permissions

Run-time permissions have two of the most significant permissions for the app, and they are

    • Read_phone_state
    • Write_external_storage/read_external_storage

Where read_phone_state is used to get DeviceID, the IMEI number. This is a reference to a number of statistical dependent compute device unique IDs. Avoid the exception that causes statistics if new permissions cause the read to be unreadable. It is recommended that the corresponding values be written to the app's local data before full support for runtime permissions, and that additional policies can be taken to reduce the impact on the statistics for new installations.

Write_external_storage/read_external_storage These two permissions are related to external storage (that is, sdcard), it is important to download the relevant application, we should explain and guide the user to grant this permission as much as possible.

A bit of advice
    • Do not use extra permissions, be cautious when adding permissions
    • Use intent to replace certain permissions, such as calling (and your product Manager PK go)
    • For some values obtained using permissions, such as DeviceID, try to store locally, the next access directly uses the local data value
    • Note that because the user can revoke some permissions, do not use the flag bit of the app local to record whether a permission is obtained.
Attention

Even if run-time permissions are supported, declare it in manifest, because the market app will match this information with the hardware device to determine whether your app is displayed on that device.

# #是否支持运行时权限
Personally feel that Marshmallow's run-time permissions are definitely a good thing for the user, but there are still a lot of things that need to be done to support it.

For a host application with a lot of dependencies, there is some work to be done because your permission request is subject to dependency.

It is recommended that you do not consider supporting the runtime permission mechanism for a short period of time, such as when the timing is ripe or when the third-party library is ready for use.

Talk about run-time permissions for Android 6.0

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.