Android - 获取运行时权限的问题

时间:2018-02-04 05:22:02

标签: java android

在我的应用程序中获得运行时间许可 以下是获取请求的方式

ActivityCompat.requestPermissions(IntroductionSlider.this,String[]{ Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_CODE);

以下是获得结果的方法

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


    boolean flag=false;
    if(requestCode == REQUEST_CODE){

        if(grantResults.length>0){
            if(grantResults[0]==PackageManager.PERMISSION_GRANTED && grantResults[1]==PackageManager.PERMISSION_GRANTED && grantResults[2]==PackageManager.PERMISSION_GRANTED){
                flag=true;
            }
        }

        if(flag){
            Toast.makeText(IntroductionSlider.this,"Granted",Toast.LENGTH_LONG).show();

            startActivity(new Intent(IntroductionSlider.this,oneTimeValidation.class));
            finish();
        }else {


            Toast.makeText(IntroductionSlider.this,"Goto to setting->Apps->My market->Permissions grant all permissions to proceed",Toast.LENGTH_LONG).show();
        }
        return;
    }

}

我的问题是尽管我拒绝运行时的某些权限。我正在获取toast “Granted” ie.in if block。不要为什么会这样 任何人都可以帮助我。

2 个答案:

答案 0 :(得分:1)

为每个权限设置布尔值&检查,如果所有权限允许,只有toast将显示权限,否则权限被拒绝。它的可行代码我已经在我的应用程序中使用了它。

参考:https://www.android-examples.com/request-check-multiple-runtime-permissions-android-marshmallow/

使用以下代码,

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

        case RequestPermissionCode:

            if (grantResults.length > 0) {

                boolean CameraPermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean ReadContactsPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                boolean ReadPhoneStatePermission = grantResults[2] == PackageManager.PERMISSION_GRANTED;

                if (CameraPermission && ReadContactsPermission && ReadPhoneStatePermission) {

                    Toast.makeText(MainActivity.this, "Permission Granted", Toast.LENGTH_LONG).show();
                }
                else {
                    Toast.makeText(MainActivity.this,"Permission Denied",Toast.LENGTH_LONG).show();

                }
            }

            break;
    }
}

答案 1 :(得分:0)

我认为您应该检查此库以获得最佳实践,这将节省您的时间并且易于管理。  https://www.androidhive.info/2017/12/android-easy-runtime-permissions-with-dexter/