如何在android 6.0+中同时提出多个权限

时间:2016-09-13 04:55:13

标签: java android android-studio android-6.0-marshmallow

我想要求用户同时接受以下权限(逐个),权限如下: checkLocationPermission,checkReadSMS,checkCallingPermission,checkReadState,checkContactWriteState。 那么,我如何在我的第一个屏幕本身中询问所有这些权限。 在这方面请帮帮我。 提前谢谢。

3 个答案:

答案 0 :(得分:1)

您必须首先检查用户手机版本是否为23。

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    askPermissions(true);
} else {
    startActivity(new Intent(PermissionsActivity.this, SplashActivity.class));
    finish();
}

如果版本是23,那么您需要询问权限。

private void askPermissions(boolean isForOpen) {
    isRationale = false;
    List permissionsRequired = new ArrayList();

    final List<String> permissionsList = new ArrayList<String>();
    if (!checkPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE))
        permissionsRequired.add("Write External Storage");
    if (!checkPermission(permissionsList, Manifest.permission.CALL_PHONE))
        permissionsRequired.add("Call phone");
    if (!checkPermission(permissionsList, Manifest.permission.READ_PHONE_STATE))
        permissionsRequired.add("Read phone state");
    if (!checkPermission(permissionsList, Manifest.permission.READ_CONTACTS))
        permissionsRequired.add("Read Contacts");
    if (!checkPermission(permissionsList, Manifest.permission.RECEIVE_SMS))
        permissionsRequired.add("Receive SMS");
    if (!checkPermission(permissionsList, Manifest.permission.GET_ACCOUNTS))
        permissionsRequired.add("Get Accounts");
    if (!checkPermission(permissionsList, Manifest.permission.ACCESS_COARSE_LOCATION))
        permissionsRequired.add("Location");
    if (!checkPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
        permissionsRequired.add("Location");

    if (permissionsList.size() > 0 && !isRationale) {
        if (permissionsRequired.size() > 0) {

        }
        if (isForOpen) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                ActivityCompat.requestPermissions(this, permissionsList.toArray(new String[permissionsList.size()]),
                        11);
            }
        }

    } else if (isRationale) {
        if (isForOpen) {

            new android.support.v7.app.AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle)
                    .setTitle("Permission Alert")
                    .setMessage("You need to grant permissions manually. Go to permission and grant all permissions.")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", getPackageName(), null);
                            intent.setData(uri);
                            startActivityForResult(intent, 123);
                        }
                    })
                    .show();
        }
    } else {
        startActivity(new Intent(PermissionsActivity.this, SplashActivity.class));
        finish();
    }
}

private boolean checkPermission(List permissionsList, String permission) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permission);
            // Check for Rationale Option
            if (!isFirst) {
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                    isRationale = true;
                    return false;
                }
            }
        }
    }
    return true;
}

on onRequestPermissionsResult您需要检查授予的权限

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case 11:
            Map<String, Integer> perms = new HashMap<String, Integer>();
            // Initial
            perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.CALL_PHONE, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.READ_CONTACTS, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.RECEIVE_SMS, PackageManager.PERMISSION_GRANTED);
            // Fill with results
            for (int i = 0; i < permissions.length; i++) {
                perms.put(permissions[i], grantResults[i]);
            }
            // Check for ACCESS_FINE_LOCATION
            if (perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    perms.get(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED &&
                    perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED &&
                    perms.get(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED &&
                    perms.get(Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED) {
                // All Permissions Granted
                startActivity(new Intent(PermissionsActivity.this, SplashActivity.class));
                finish();
            } else {
                // Permission Denied
                Toast.makeText(this, "Some Permission is Denied.", Toast.LENGTH_SHORT)
                        .show();
                isFirst = false;
                askPermissions(true);
            }
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }
}

如果用户已将权限设置为永不再询问,则将打开应用程序设置屏幕。用户将允许/拒绝那里的许可。您需要再次检查activityResult。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    askPermissions(true);
}

答案 1 :(得分:0)

Kotlin 版本

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment

class MyFragment : Fragment() {

companion object {
    val TAG: String = MyFragment::class.java.simpleName
    var PERMISSIONS = arrayOf(
        Manifest.permission.CAMERA,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
}

private val permReqLauncher =
    registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
        val granted = permissions.entries.all {
            it.value == true
        }
        if (granted) {
            displayCameraFragment()
        }
    }

private fun takePhoto() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        displayCameraFragment()
    }
    activity?.let {
        if (hasPermissions(activity as Context, PERMISSIONS)) {
            displayCameraFragment()
        } else {
            permReqLauncher.launch(
                PERMISSIONS
            )
        }
    }
}

// util method
private fun hasPermissions(context: Context, permissions: Array<String>): Boolean = permissions.all {
    ActivityCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
}

private fun displayCameraFragment() {
    // open camera fragment
}
}

答案 2 :(得分:-1)

if (!hasPermissions()){
                        // your app doesn't have permissions, ask for them.
                        requestNecessaryPermissions();
                    }
                    else {
                        // your app already have permissions allowed.
                        // do what you want.
                    }


private boolean hasPermissions() {
        int res = 0;
        // list all permissions which you want to check are granted or not.
        String[] permissions = new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        for (String perms : permissions){
            res = checkCallingOrSelfPermission(perms);
            if (!(res == PackageManager.PERMISSION_GRANTED)){
                // it return false because your app dosen't have permissions.
                return false;
            }

        }
        // it return true, your app has permissions.
        return true;
    }

    private void requestNecessaryPermissions() {
        // make array of permissions which you want to ask from user.
        String[] permissions = new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // have arry for permissions to requestPermissions method.
            // and also send unique Request code.
            requestPermissions(permissions, REQUEST_CODE_STORAGE_PERMS);
        }
    }

    /* when user grant or deny permission then your app will check in
      onRequestPermissionsReqult about user's response. */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grandResults) {
        // this boolean will tell us that user granted permission or not.
        boolean allowed = true;
        switch (requestCode) {
            case REQUEST_CODE_STORAGE_PERMS:
                for (int res : grandResults) {
                    // if user granted all required permissions then 'allowed' will return true.
                    allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
                }
                break;
            default:
                // if user denied then 'allowed' return false.
                allowed = false;
                break;
        }
        if (allowed) {
            // if user granted permissions then do your work.
            dispatchTakePictureIntent();
        }
        else {
            // else give any custom waring message.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
                    Toast.makeText(MainActivity.this, "Camera Permissions denied", Toast.LENGTH_SHORT).show();
                }
                else if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
                    Toast.makeText(MainActivity.this, "Storage Permissions denied", Toast.LENGTH_SHORT).show();
                }
            }

        }
    }

按照本教程,在本教程中要求多个权限

Android 6.0 Runtime Permissions