A util to solve the problem of dynamic application permission

Preface

Android has a concept of dynamic permission application since API23, which is Android 6.0. Here's a util to solve this problem. But before the code, I have something to say:

After entering the first installation application, you will need permission. Generally speaking, this permission will be after the advertisement page and before entering the main page, because if you don't get permission before entering, some functions will not run. Look at the interface behind the picture carefully, only the root path is displayed, and the following is empty. Then you will have another picture that you click allow to enter again:

Use

Direct code:

public class PermissionsUtil {
    // read-write permission
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    /**
     * Check that the application is authorized to write to device storage
     * If the application does not have permissions, the user is prompted to grant them
     *
     * @param activity Activity
     */
    public static void verifyStoragePermissions(Activity activity) {
        // Check that the application is authorized to write to device storage
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // If the application does not have permissions, the user is prompted to grant them
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }
}

Then in the foreword:

verifyStoragePermissions(this);
/**
 * @param requestCode  Request code
 * @param permissions  Jurisdiction
 * @param grantResults Award result
 */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case 1:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                LogUtil.i(getResources().getString(R.string.succeed));
            } else {
                Toast.makeText(this, getResources().getString(R.string.failed), Toast.LENGTH_LONG).show();
                finish();
            }
            break;
        default:
    }
}

Of course, don't forget to apply for basic permissions in Android manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

Tags: Android xml

Posted on Sun, 05 Jan 2020 14:43:42 -0800 by pbsonawane