如何读取当前权限状态?

时间:2017-11-14 05:55:14

标签: android permissions

在我的应用中,我需要GPS才能找到用户。我希望我的应用程序提供以下类型的结果。

1.The current location.(Success)
2.Failed to get current location because of device error or something else. (Failed)
3.The user refused the permission. (Permission denied)

我使用LocationManager来完成这项工作。

locationManager = (LocationManager)mActivity.getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

如果权限被拒绝,则该位置将为null。

但是如果功能失败,我不知道该位置是什么。而且我不确定该位置是否为空且用户拒绝打开GPS是相同的。

使用以下代码,我可能知道是否在AndroidManifest.xml中添加了权限。但我无法得到我需要的信息。

boolean getLocationOn = (PackageManager.PERMISSION_GRANTED ==   
           pm.checkPermission("android.permission.ACCESS_FINE_LOCATION", "my_package"));

3 个答案:

答案 0 :(得分:0)

使用以下代码检查和请求权限

private void checkAndRequestPermissions() {
    int camera = ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA);
    int storage = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
    int loc = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION);
    int loc2 = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION);
    int logs = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_LOGS);
    int networkstate = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_NETWORK_STATE);
    int internet = ContextCompat.checkSelfPermission(this, android.Manifest.permission.INTERNET);
    int wifistate = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_WIFI_STATE);
    int externalstorage = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE);
    int phonestate = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE);
    int wakelock = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WAKE_LOCK);
    int alarm = ContextCompat.checkSelfPermission(this, android.Manifest.permission.SET_ALARM);
    int audio = ContextCompat.checkSelfPermission(this, android.Manifest.permission.RECORD_AUDIO);
    int accounts = ContextCompat.checkSelfPermission(this, android.Manifest.permission.GET_ACCOUNTS);
    int contacts = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS);
    List<String> listPermissionsNeeded = new ArrayList<>();

    if (camera != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.CAMERA);
    }
    if (storage != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
    if (loc2 != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
    }
    if (loc != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
    }
    if (logs != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.READ_LOGS);
    }
    if (networkstate != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.ACCESS_NETWORK_STATE);
    }
    if (internet != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.INTERNET);
    }
    if (wifistate != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.ACCESS_WIFI_STATE);
    }
    if (externalstorage != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.READ_EXTERNAL_STORAGE);
    }
    if (phonestate != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.READ_PHONE_STATE);
    }
    if (wakelock != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.WAKE_LOCK);
    }
    if (alarm != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.SET_ALARM);
    }
    if (audio != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.RECORD_AUDIO);
    }
    if (accounts != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.GET_ACCOUNTS);
    }
    if (contacts != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.READ_CONTACTS);
    }
    if (!listPermissionsNeeded.isEmpty()) {
        ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
    }
}

调用checkAndRequestPermissions()来检查和请求权限。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    checkAndRequestPermissions();
}

答案 1 :(得分:0)

创建一种检查权限的方法。

public static final int MULTIPLE_PERMISSIONS = 15;
String[] permissions= new String[]
{
    Manifest.permission.ACCESS_COARSE_LOCATION,
    Manifest.permission.ACCESS_FINE_LOCATION

};

下面的功能会请求权限。

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

    if (requestCode == MULTIPLE_PERMISSIONS) {

        Log.v("Nopermissionz", "No permission granted , " + permissions.length);

        if (permissions.length == 2
                && grantResults[0] == PackageManager.PERMISSION_GRANTED
                && grantResults[1] == PackageManager.PERMISSION_GRANTED) {

            Log.v("Nopermission1", "Permission granted , " + permissions.length);

        } else {
            Log.v("Nopermission2", "No permission granted");
            Snackbar.make(findViewById(android.R.id.content), "Please allow this App with some permissions", Snackbar.LENGTH_INDEFINITE)
                    .setAction("SETTINGS", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent();
                            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", getPackageName(), null);
                            intent.setData(uri);
                            startActivity(intent);
                        }
                    })
                    .show();
        }
    }
}

调用方法 checkPermissions()以检查是否授予了权限。

private  boolean checkPermissions() 
{
    int result;
    List<String> listPermissionsNeeded = new ArrayList<>();
    for (String p:permissions) 
    {
        result = ContextCompat.checkSelfPermission(MainActivity.this,p);
        if (result != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(p);
        }
    }
    if (!listPermissionsNeeded.isEmpty()) {
        ActivityCompat.requestPermissions(MainActivity.this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),MULTIPLE_PERMISSIONS );
        return false;
    }
    return true;
}

答案 2 :(得分:0)

首先实现一个像这样的onRequestPermissionResult:

@Override 
public void onRequestPermissionsResult(int requestCode,
            String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_ACCESS_LOCATION: { 
                // If request is cancelled, the result arrays are empty. 
                if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, do your stuff!
                locationManager = (LocationManager)mActivity.getSystemService(Context.LOCATION_SERVICE);
                Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location != null) {
                } else { 
                //location wasn't found
                }

            } else { 

               //user denied permission additionally you can check  
               //ActivityCompat.shouldShowRequestPermissionRationale if user checked on "do not show again" while clicking deny
            } 
            return; 
        } 
     } 
}