Failed to create directory in Android Oreo (API 26)

邮差的信 提交于 2019-12-24 04:24:11

问题


I have already read the documentation for Android Oreo's Behavior and changes.

I know there is different procedure to create file directory for Android Oreo (API 26)

Code :

 File mediaStorageDir = null;

    if (Build.VERSION.SDK_INT >= 26) {
        mediaStorageDir = new File(Environment.getExternalStorageDirectory().toString(), "MyDirectory");
        Log.v("HEREEEEE","YES");
    } else {
        mediaStorageDir = new File(Environment.getExternalStorageDirectory().toString()
                + File.separator + "MyDirectory");
    }

    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Toast.makeText(RecordVideoActivity.this, "Failed to create directory MyDirectory.",
                    Toast.LENGTH_LONG).show();
            return null;
        }
    }

But every time i am getting toast of Failed to create directory MyDirectory. I am able to Log.v("HEREEEEE","YES"); also but don't know it's not creating directory.

Advanced help would be appreciated.!


回答1:


Post Lollipop you have to ask for permission, you can look for the answer in this post here

public  boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
            return true;
        } else {

            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }
}

Permission result callback:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //Create your Directory here
    }
}


来源:https://stackoverflow.com/questions/47217725/failed-to-create-directory-in-android-oreo-api-26

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!