Manage App Permissions on Android Marshmallow 6

At the last of Google I/O conference. Google has announced its new version of Android called Marshmallow. Google has introduced some new features. One of the biggest new feature is the management of permissions granted to applications that are downloaded from the Play Store.

Permissions

With Marshmallow, we no longer need to validate the permissions during the installation, but when using the application. the user will have the possibility to choose the permissions at the time of its use.

We can now display the permissions requested by the application from the menu dedicated to the management of permissions for applications that are already installed.

Depending on the application, you can enable or disable access to the camera, location, microphone, contacts, sms, mobile or SD card memory, etc ...

when refusing the authorization of permission, we will not be able to use all of the features associated with this permission properly. In this article, I present how to use permissions on Android Marshmallow.

Declaring a permission

The first step is to declare the permissions of the application in the manifestas we usually do. We'll take the example of access to the contact.
<uses-permission-sdk-m android:name="android.permission.READ_CONTACTS" />
<uses-permission-sdk-m android:name="android.permission.WRITE_CONTACTS" />

Check permission

I present the methods to be used generally

  • the method "checkSelfPermission" allows checking the access authorization to functionality that requires permission and this each time we need to use it.
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,

Manifest.permission.WRITE_CALENDAR);

"ContextCompat" lets you use the context independently of the version of Android. The result of the invocation of this method is either an authorization (Granted) or refusal (Denied).

  • The "shouldShowRequestPermissionRationale" method is used to validate if permission has was already checked by the user to avoid checking the authorization again.
  • The "requestPermissions" method is used to ask permission to the user waiting for confirmation.

Create the PermissionUtil class

In PermiisionUtil class. we define Methods related to the verification of permissions.
In this class, two methods are used:


  • The first method  "VerifyPermissions" checks different permissions that you want to grant the application. If the application has already received approval for these permissions, the method returns TRUE. Otherwise, it returns FALSE.
  • The second method “requestContactsPermissions” will ask permissions for permissions to access to contacts, like reading and writing new contacts.

Here is the implementation of PermissionUtil class :
public abstract class PermissionUtil {

   public static boolean verifyPermissions(int[] grantResults) {
       // At least one result must be checked.
       if(grantResults.length < 1){
           return false;
       }

       // Verify that each required permission has been granted, otherwise return false.
       for (int result : grantResults) {
           if (result != PackageManager.PERMISSION_GRANTED) {
               return false;
           }
       }
       return true;
   }

   public static boolean requestContactsPermissions(Activity activity) {

       boolean requestPermission;

       if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
               Manifest.permission.READ_CONTACTS)
               || ActivityCompat.shouldShowRequestPermissionRationale(activity,
               Manifest.permission.WRITE_CONTACTS)) {

           // Provide an additional rationale to the user if the permission was not granted
           // and the user would benefit from additional context for the use of the permission.
           // For example, if the request has been denied previously.

           requestPermission =  true;
       } else {
           // Contact permissions have not been granted yet. Request them directly.

           requestPermission =  true;
       }
       return requestPermission;
   }

}
Then you have to manage permissions from the mainActivity where the following variables are declared:
private static final int REQUEST_CONTACTS = 1;

private static String[] PERMISSIONS_CONTACT = {Manifest.permission.READ_CONTACTS,
       Manifest.permission.WRITE_CONTACTS};
Here, the REQUEST_CONTACTS is used to see if the permission is allowed or not.
We declare the different permissions to use for access to the contact in the table PERMISSIONS_CONTACT

Callback Implementation

It’s then necessary to proceed to the implementation of "OnRequestPermissionsResultCallBack" interface in the acitivity of application.
MainActivity extends AppCompactActivity implements OnRequestPermissionsResultCallback
This interface implements the onRequestPermissionsResult method. This is the most important part. When we receives the access permission request to the contacts via requestCode, you need to check if you already allowed access to the application. here we need to use the verifyPermissions method of PermissionsUtil class
If permission is granted, it displays a message “Contacts Permissions have been granted”
Otherwise, the message to be displayed will be "Contacts permissions were NOT granted."
The code for this method is as follows :
@Override
public void onRequestPermissionsResult(int requestCode,
                                      String permissions[], int[] grantResults) {

   if (requestCode == REQUEST_CONTACTS) {
       Log.i(TAG, "Received response for contact permissions request.");

       // We have requested multiple permissions for contacts, so all of them need to be
       // checked.
       if (PermissionUtil.verifyPermissions(grantResults)) {
           // All required permissions have been granted, display contacts fragment.
           Snackbar.make(mLayout, R.string.permision_available_contacts,
                   Snackbar.LENGTH_LONG)
                   .show();
       } else {
           Log.i(TAG, "Contacts permissions were NOT granted.");
           Snackbar.make(mLayout, R.string.permissions_not_granted,
                   Snackbar.LENGTH_LONG)
                   .show();
       }

   } else {
       super.onRequestPermissionsResult(requestCode, permissions, grantResults);
   }
}
Now it only remains that applying permission checking when the user is going to access the contact.
In this example, verification uses the requestContactsPermissions method of PermissionsUtil class.
boolean requestPermission = PermissionUtil.requestContactsPermissions(this);

Request Permissions

A SnackBar will appear to say that we will proceed to verify permissions. Pressing the "OK" message, we call the requestPermissions function that will display a PopUp asking the user if he wants to grant this permission or it will rejected.

here the full implementation of the requetContactsPermissions method :
private void requestContactsPermissions() {

   boolean requestPermission = PermissionUtil.requestContactsPermissions(this);

   if (requestPermission == true){

       Log.i(TAG,
               "Displaying contacts permission rationale to provide additional context.");

       // Display a SnackBar with an explanation and a button to trigger the request.
       Snackbar.make(mLayout, R.string.permission_contacts_rationale,
               Snackbar.LENGTH_INDEFINITE)
               .setAction(R.string.ok, new View.OnClickListener() {
                   @Override
                   public void onClick(View view) {
                       ActivityCompat
                               .requestPermissions(MainActivity.this, PERMISSIONS_CONTACT,
                                       REQUEST_CONTACTS);
                   }
               })
               .show();

   }

   else {

       ActivityCompat.requestPermissions(this, PERMISSIONS_CONTACT, REQUEST_CONTACTS);

   }

}

Check Permission

Now, calling the last method when the application will need to check the access permission to contact. In this tutorial, we call this method when pressing on the "CHECK PERMISSION" button.


Implementation of OnClick Method :
@Override
public void onClick(View v) {
  
   switch (v.getId()) {
       case R.id.button_check_permissions:
           requestContactsPermissions();
           break;

       default:
           break;
   }

}

Here is the complete code of MainActivity :
public class MainActivity extends AppCompatActivity implements
       OnRequestPermissionsResultCallback, OnClickListener{

   public static final String TAG = "PermissionActivity";

   private View mLayout;
   Button mButtonCheckPermission = null;

   private static final int REQUEST_CONTACTS = 1;
   private static String[] PERMISSIONS_CONTACT = {Manifest.permission.READ_CONTACTS,
           Manifest.permission.WRITE_CONTACTS};

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       initView();
   }

   private void initView() {
       mButtonCheckPermission = (Button) findViewById(R.id.button_check_permissions);
       mButtonCheckPermission.setOnClickListener(this);

       mLayout = findViewById(R.id.sample_main_layout);

   }

   @Override
   public void onClick(View v) {
      
       switch (v.getId()) {
           case R.id.button_check_permissions:
               requestContactsPermissions();
               break;

           default:
               break;
       }

   }

   private void requestContactsPermissions() {

       boolean requestPermission = PermissionUtil.requestContactsPermissions(this);

       if (requestPermission == true){

           Log.i(TAG,
                   "Displaying contacts permission rationale to provide additional context.");

           // Display a SnackBar with an explanation and a button to trigger the request.
           Snackbar.make(mLayout, R.string.permission_contacts_rationale,
                   Snackbar.LENGTH_INDEFINITE)
                   .setAction(R.string.ok, new View.OnClickListener() {
                       @Override
                       public void onClick(View view) {
                           ActivityCompat
                                   .requestPermissions(MainActivity.this, PERMISSIONS_CONTACT,
                                           REQUEST_CONTACTS);
                       }
                   })
                   .show();

       }

       else {

           ActivityCompat.requestPermissions(this, PERMISSIONS_CONTACT, REQUEST_CONTACTS);

       }

   }

   @Override
   public void onRequestPermissionsResult(int requestCode,
                                          String permissions[], int[] grantResults) {

       if (requestCode == REQUEST_CONTACTS) {
           Log.i(TAG, "Received response for contact permissions request.");

           // We have requested multiple permissions for contacts, so all of them need to be
           // checked.
           if (PermissionUtil.verifyPermissions(grantResults)) {
               // All required permissions have been granted, display contacts fragment.
               Snackbar.make(mLayout, R.string.permision_available_contacts,
                       Snackbar.LENGTH_LONG)
                       .show();
           } else {
               Log.i(TAG, "Contacts permissions were NOT granted.");
               Snackbar.make(mLayout, R.string.permissions_not_granted,
                       Snackbar.LENGTH_LONG)
                       .show();
           }

       } else {
           super.onRequestPermissionsResult(requestCode, permissions, grantResults);
       }
   }
}


No comments:

Post a Comment

Genuine websites to earn money.

If you are interested in PTC sites then this article is for you. I have personally tried many of the sites and found that the best thing ...