Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Android 6.0 Permissions Helper

Requires Android Support v4 and v7, for example:

compile 'com.android.support:support-v4:24.2.1'
compile 'com.android.support:appcompat-v7:24.2.1'

These versions may be outdated when you read this, so perform a check.

Example usage:

import android.Manifest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

public class YourActivity extends AppCompatActivity {
    private static final String LOG_TAG = "activity";
    private static final int PERMISSIONS_REQUEST_CODE = 1;
    private AndroidPermissions mPermissions;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        // these permissions have to match the ones you declared in the manifest
        //
        // If you need WRITE_SETTINGS, check the following:
        // http://stackoverflow.com/questions/32083410/cant-get-write-settings-permission
        mPermissions = new AndroidPermissions(this,
                Manifest.permission.INTERNET,
                Manifest.permission.BLUETOOTH);
    }

    private void doSomething() {
        if (mPermissions.checkPermissions()) {
            myImplementation();
        } else {
            Log.i(LOG_TAG, "Some needed permissions are missing. Requesting them.");
            mPermissions.requestPermissions(PERMISSIONS_REQUEST_CODE);
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        Log.i(LOG_TAG, "onRequestPermissionsResult");

        if (mPermissions.areAllRequiredPermissionsGranted(permissions, grantResults)) {
            myImplementation();
        } else {
            onInsufficientPermissions();
        }
    }
    
    private void onInsufficientPermissions() {
        //your implementation to show the user that the required permissions have not been granted
    }
    
    private void myImplementation() {
        //your implementation here
    }
}
import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Helper to handle the new Android 6.0 Permissions requests.
* @author gotev (Aleksandar Gotev)
*/
public class AndroidPermissions {
private Activity mContext;
private String[] mRequiredPermissions;
private List<String> mPermissionsToRequest = new ArrayList<>();
public AndroidPermissions(Activity context, String... requiredPermissions) {
mContext = context;
mRequiredPermissions = requiredPermissions;
}
/**
* Checks if all the required permissions are granted.
* @return true if all the required permissions are granted, otherwise false
*/
public boolean checkPermissions() {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1)
return true;
for (String permission : mRequiredPermissions) {
if (ContextCompat.checkSelfPermission(mContext, permission) != PackageManager.PERMISSION_GRANTED) {
mPermissionsToRequest.add(permission);
}
}
if (mPermissionsToRequest.isEmpty()) {
return true;
}
return false;
}
/**
* Requests the missing permissions.
* The activity from which this method is called has to implement
* {@link Activity#onRequestPermissionsResult(int, String[], int[])}
* and then, inside it, it has to call the method
* {@link AndroidPermissions#areAllRequiredPermissionsGranted(String[], int[])} to check that all the
* requested permissions are granted by the user
* @param requestCode request code used by the activity
*/
public void requestPermissions(int requestCode) {
String[] request = mPermissionsToRequest.toArray(new String[mPermissionsToRequest.size()]);
StringBuilder log = new StringBuilder();
log.append("Requesting permissions:\n");
for (String permission : request) {
log.append(permission).append("\n");
}
Log.i(getClass().getSimpleName(), log.toString());
ActivityCompat.requestPermissions(mContext, request, requestCode);
}
/**
* Method to call inside
* {@link Activity#onRequestPermissionsResult(int, String[], int[])}, to check if the
* required permissions are granted.
* @param permissions permissions requested
* @param grantResults results
* @return true if all the required permissions are granted, otherwise false
*/
public boolean areAllRequiredPermissionsGranted(String[] permissions, int[] grantResults) {
if (permissions == null || permissions.length == 0
|| grantResults == null || grantResults.length == 0) {
return false;
}
LinkedHashMap<String, Integer> perms = new LinkedHashMap<>();
for (int i = 0; i < permissions.length; i++) {
if (!perms.containsKey(permissions[i])
|| (perms.containsKey(permissions[i]) && perms.get(permissions[i]) == PackageManager.PERMISSION_DENIED))
perms.put(permissions[i], grantResults[i]);
}
for (Map.Entry<String, Integer> entry : perms.entrySet()) {
if (entry.getValue() != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment