Monday, March 6, 2017

android runtime permissions


private static final int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 0x1000;

private void requestPermissions() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Log.e(TAG, "shouldShowRequestPermissionRationale()");
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
            Log.e(TAG, "requestPermissions()");
        }
    }
}

@Overridepublic void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE:
            // If request is cancelled, the result arrays are empty.            if (grantResults.length > 0                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.e(TAG, "permission Granted");
            } else {
                Log.e(TAG, "permission Denied");
            }
            break;
        default:
            break;
    }
}

No comments:

Post a Comment