Android marshmallow permissions example

Android Marshmallow Runtime Permission Example

Android permissions have been divided into two groups from android 6.0 which build name is android marshmallow. And the related SDK version is 23. This article will tell you the difference between those groups with examples.

1. Android Permission Groups.

1.1 Normal Permissions.

  1. One group of permission is called normal permissions which do not need users to allow at runtime, you just need to declare them in the AndroidManifest.xml file as usual.
  2. All the permissions except runtime permissions are all normal permissions.

1.2 Dangerous ( Runtime ) Permissions

  1. Another group of permission is called dangerous permissions, they are all related to android OS core operations.
  2. They also need to be declared in the AndroidManifest.xml file, and they need users to allow when the app runs. This can give app users the choice of android permission selection.
  3. The android dangerous permissions are divided into groups, if you allow one permission in a group, then all the group permissions are granted to the android application. That means the android app can use all the permissions in the group.

2. Android Runtime Permission WorkFlow.

  1. If you run an app with an android SDK version smaller than 23, even your app requires dangerous ( runtime ) permissions, the app does not need the user to grant the required permission to run.
  2. But if the SDK version is bigger than 23 then when the app requires dangerous permissions, then android os will popup a window to let the app user to choose whether grant permission to the app or not.

2.1 Android Runtime Permission Check And Require Code.

  1. Use the below code to check whether the required permission has been granted to the current app or not.
  2. If required runtime permission is not granted, use the below code to require the app user to allow it.
  3. Overwrite the below method in your activity, and in this method, you can get the user grant result. The requestCode input parameter is just the requestCode you used in step 2.
  4. If you do not require the dangerous permissions in SDK version 23 or higher before you use, then you will see the below exceptions.
  5. After you uninstall the android app, all the permissions granted to it will be removed also.

3. Android Runtime Permission Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/QkuIiu_baHg

  1. Because there are three normal android permissions declared in the AndroidManifest.xml file, so those permissions can be listed when you click the first button.
  2. If you want to manually deny runtime permissions that have been granted to the app. You can follow the below steps.
  3. Click Settings —> Apps.
  4. Click the application you want to operate.
  5. Click Permissions menu item.
  6. Toggle the permissions button to manually turn on / off related permissions.
Читайте также:  Titan quest android не запускается

Источник

Android Working with Marshmallow (M) Runtime Permissions

Android is a privilege separated operating system, i.e. each application in android is separated from another through a distinct id, and each application file / data is private to that application only. Each Android application is started in its own process thus are isolated from all other applications (even from system / default applications). As a result an Android application can’t access any file or data outside its scope until and unless the file or data is shared with the application.

So, the conclusion is that if an application needs anything outside its scope, then it should request for permission to the user. Android comes with a set of predefined permissions (System permissions) for certain tasks. Every application can request required permissions. For example, an application may declare that it requires network access. It can also define new permissions.

1. Permission Workflow before and from M (API 23)

Now the question arises how an application can request for or get permission? Or rather, what workflow the developer should follow to request and get permission for the app? Let us have a look. The permission model / workflow has been changed from API 23 – Android M.

> Permission Model before M (API 23): Before API 23, the permission model was simpler to the developer but offered less control and security to the user – requested permissions are presented to the user before installing the application. The user needs to decide whether to give these permissions to the application and install it or to deny as a whole and don’t install the application. Permissions cannot be denied or granted after the installation. Thus developers were required only to declare all needed permissions in the manifest and then just forget; if the app is running then it has all the requested permissions.

> Permission Model from M (API 23): With Android 6.0 Marshmallow (API 23), a new runtime permission model has been introduced. According to this model users are not prompted for permission at the time of installing the app, rather developers need to check for and request permission at runtime (i.e. before performing any action that may require the particular permission), users can then allow or deny the permission, users can also grant or revoke permission anytime from settings. Making the user experience very secure on an Android device. But inversely this feature imposes a great deal of effort on development. Therefore developers have to handle all the use cases. Thankfully, requesting Android runtime permissions, is not that difficult.

Note: According to Google, beginning with Android 6.0 (API level 23), users can revoke permissions from any app at any time, even if the app targets a lower API level. You should test your app to verify that it behaves properly when it’s missing a needed permission, regardless of what API level your app targets.

Читайте также:  Football manager touch 2021 для андроид

2. Permission levels

System permissions have different protection levels. The two most important protection levels are normal and dangerous permissions.

Normal Permissions: Those permissions which will have very little or zero effect on users privacy or security are categorized as normal permissions. The system itself grants normal permissions when requested instead of prompting to the user. Examples would be ACCESS_WIFI_STATE, WAKE_LOCK etc.

Dangerous Permissions: Those permissions which may have a greater effect on users privacy or security are categorized as dangerous permissions. Examples would be the ability to read the user’s contacts READ_CONTACTS. If an app requests a dangerous permission, the user has to explicitly grant the permission to the app.

Here is the detailed information about permissions and their groups.

So now let us start with creating a sample app.

3. Creating Android Project

1. Create a new project in Android Studio from File ⇒ New Project and fill the project details.

2. Open strings.xml and add the below string values.

3. Open build.gradle (app level) and make sure that you have set minSdkVersion and targetSdkVersion as we have to support the permissions model in lower versions also. I am keeping minSdkVersion to 17 and targetSdkVersion to 23.

3.1 Requesting Single Permission

4. Though we will request the permissions at runtime, we should add it to the Manifest also, so that the user will be prompted first time when going to use the permission, and then the system will remember user’s decision until user updates from the settings. We will start with the WRITE_EXTERNAL_STORAGE_PERMISSION. Add the storage permission to your AndroidManifest.xml just before the application tag.

5. Open the layout file of main activity (activity_main.xml) and add the below xml. This layout contains few buttons to test various permission scenarios.

The above layout generates a screen something like this.

6. Now open MainActivity.java and add the below code in FAB click event.

Explanation:

> We checked for permission with checkSelfPermission() Method to check if the app already has permission to write on external storage. If it has then continue to else part, otherwise go to next step.

> Here we used shouldShowRequestPermissionRationale() method to check if we should show the explanation for the permission or not, if this returns true then we showed an alert dialog with explanation, and on the positive button click we requested the permission. If shouldShowRequestPermissionRationale returns false then we requested permission straightforward.

> We have successfully requested permission so far. We just need to override the method onRequestPermissionsResult to receive the result. In that method first we checked the requested code with our declared constant requestCode == EXTERNAL_STORAGE_PERMISSION_CONSTANT then checked if length of grantResult is greater than 0, so that it contains the user’s decision, then we cheked if the value of 0 index of the grant result, if the value is equal to PackageManager.PERMISSION_GRANTED then it means that the user has authorised the permission and we can continue our work, otherwise in the else part we can again request for permission with explanation.

> Add SharedPreferences, think of a situation where the user has denied permission by checking “Never Ask Again”. In that scenario the shouldShowRequestPermissionRationale method will return false and requestPermissions method will do just nothing. So we need to remember whether we ave priorly requested for permission or not, even after the app restarts. For that purpose we will use SharedPreferences, we will use the permission string as the key and boolean true or false as value.

Читайте также:  Android custom notification view

Below is the complete code of MainActivity.java

3.2 Requesting Multiple Permissions

Think of a scenario where you might need to ask for multiple permissions. For this, instead of requesting multiple permissions in multiple dialogs, we can prompt all the permissions in a single dialog where permissions will be scrolled through one after another. Now we’ll test this case by creating a new activity.

7. Create a new Activity and name it as MultiplePermissionsActivity.java. Open the layout file this activity (activity_multiple_permissions.xml) and add the below layout code.

8. Initialize btnLaunchMultiplePermission inside oncreate on MainActivity.java, and implement onClickListener to open MultiplePermissionsActivity on click.

9. Add the below permissions to AndroidManifest.xml file.

10. Open MultiplePermissionsActivity.java and modify the code as below.

What we’ve done here is that created and string array with required permissions. While checking for permissions, checked by all elements of the array. The only exception is in while checking with SharedPreferences, here we’ve checked with only the first string, the reason is that for storing shared preferences on string is enough and only one shared preference can tell us whether we’ve already requested for permissions or not (as we are requesting for all permissions in one go).

In the onRequestPermissionsResult() method we used a for loop to determine whether all permissions are granted or not. If a single permission is not granted then we will not proceed further.

3.3 Requesting Permission From Fragment

We will now move forward to requesting permission from Fragments. Now let us take a different approach. We will request for Phone State permission (we will actually do nothing with the permissions, we just ask for the permissions and will show the permission we’ve got).

11. Create a new Activity and name it as FragmentPermissionActivity.java. Fill the required details and check Use a Fragment.

12. Initialize btnLaunchPermissionFragment inside oncreate on MainActivity.java, and implement onClickListener to open FragmentPermissionActivity on click.

13. Add below permission to AndroidManifest.xml

14. Open PermissionsFragment.java and modify the code as below.

So everything here is almost same when you request for permission from fragment or activity, except for that you should not use ActivityCompat.requestPermissions when requesting from Fragment instead use the inbuilt method of fragment.

I hope this article gave you very good overview of Marshmallow permission model. Feel free to ask any queries / doubts in comments section below.

What’s Next?

Although this article explains very well about Runtime Permissions, it’s still very tedious task implementing permissions and its needs lot of code. If you want to quickly add runtime permissions, consider using Dexter library.

Rivu Chakraborty is a Sr. Tech. Member of Institution of Engineers(India), Diploma holder Engineer in Computer Science. He is presently at MaxMobility Pvt. Ltd. as a Sr. Software Engineer (Android)

Источник

Оцените статью