我们是否需要在 Marshmallow 中明确请求 AndroidManifest.xml 以外的权限?

Do we need to explicitly ask for the permission other than AndroidManifest.xml in Marshmallow?

在低于棉花糖的 Android 版本中,我可以 运行 我的应用程序将文件写入外部存储。在这些系统中,权限是在安装应用程序时授予的。但是当我尝试在棉花糖中 运行 我的应用程序时,它在安装时显示 "the app need no permissions"。在我执行写入功能时应用程序意外退出。

通常设备会在第一次打开时要求授予对每个应用程序的权限。但在我的应用程序中也不会发生这种情况。

您必须自己为 Android 6.0+ (Marshmallow) 提供运行时权限处理。有关详细信息,请参阅 here

在AndroidM及以上,你必须请求分类为"dangerous"的权限。您可以找到需要申请的权限的完整列表 here

但是,您可以通过将 compileSDK 和 targetSDK 设置为 < 23 来避免请求。请注意,这会阻止您使用任何 API 23+ 功能。

您请求这样的权限:

ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},//Your permissions here
                1);//Random request code

通过以下操作检查用户是否 运行 API 23+:

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
    //Request: Use a method or add the permission asking directly into here.
}

如果你需要检查结果,你可以这样做:

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

          // If request is cancelled, the result arrays are empty.
          if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.          
            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}