在运行时授予WRITE_EXTERNAL_STORAGE权限时,应用程序无法访问SD卡

时间:2015-09-09 05:56:44

标签: android android-permissions android-6.0-marshmallow

android M 中访问sdcard必须在运行时授予权限时强行停止并手动启动app,如何以编程方式实现?

但是,如果应用程序强制停止并重新启动,则可以访问sdcard。

AndroidManifest.xml:

uses-permission-sdk-m android:name="android.permission.WRITE_EXTERNAL_STORAGE


     /* **Checking permission **
        if doesn't have request
         else
         browse file directory       
    */

    String[] perm = { Manifest.permission.WRITE_EXTERNAL_STORAGE };
    if (checkSelfPermission(perm[0]) == PackageManager.PERMISSION_DENIED) {


                    requestPermissions(perm, REQ);

                } else {

                    Explore(); //method to browse file directory
                }

onRequestPermissionsResult

   @Override
public void onRequestPermissionsResult(int requestCode,
        String[] permissions, int[] grantResults) {
    // TODO Auto-generated method stub

    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {  

   //Not able to browse SD card until restart application


       Explore(); //method to browse file directory


    } else {
        Log.i("onRequestPermissionsResult", " Request denied");
    }

    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}

2 个答案:

答案 0 :(得分:9)

您需要重新启动应用程序才能获得WRITE_EXTERNAL_STORAGE权限(其他一些权限)。这是因为此权限实际上是Linux权限。在这种情况下,Android的最新预览版本不会重新启动应用程序,但Google可能会在稍后添加。

您可以使用此代码进行重启:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    // Write external store permission requires a restart
    for (int i = 0; i < permissions.length; i++)
        if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permissions[i]) &&
                grantResults[i] == PackageManager.PERMISSION_GRANTED) {
            Log.i(TAG, "Restarting application");

            // Schedule start after 1 second
            PendingIntent pi = PendingIntent.getActivity(
                    this,
                    0,
                    getIntent(),
                    PendingIntent.FLAG_CANCEL_CURRENT);
            AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            am.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, pi);

            // Stop now
            System.exit(0);
        }
}

编辑:您可以在此处找到与Linux权限相关联的Android权限列表: https://android.googlesource.com/platform/frameworks/base/+/master/data/etc/platform.xml

答案 1 :(得分:0)

您可以在以下条件下检查SD卡是否可用

if (android.os.Environment.getExternalStorageState().equals(
        android.os.Environment.MEDIA_MOUNTED)) {

 //Check for the file
 File appFolder = new File(Environment.getExternalStorageDirectory() + File.separator
            + context.getString(R.string.app_name));

 boolean exist = appFolder.exists();
}