File not found exception when reading external storage

时光怂恿深爱的人放手 提交于 2019-12-11 12:06:29

问题


Earlier the code was working totally fine, and even now it works fine for pre Android 6 devices, but in my Nexus 5, 6.0.1, I am unable to access data from external storage.

It shows File not Found Exception

java.io.FileNotFoundException: /storage/emulated/0/Download/********/*****: open failed: ENOENT (No such file or directory)

For writing the data to storage, I am asking for runtime storage permission and that part seems to be fine.


回答1:


Since your code is working fine in Pre-Marshmallow devices, looks like you've not added runtime permissions in your app.

Starting from Android M, you need to request for permissions at runtime, as mentioned in the docs :

Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app.

Read more about Requesting permissions at runtime in Android here




回答2:


Make this in you onCreate() method of main activity:

if (currentapiVersion > android.os.Build.VERSION_CODES.LOLLIPOP){
    // Do something for lollipop and above versions
    checkPermission();
    if (!checkPermission()) {
        requestPermission();
    }
}

And this code out side onCreate():

private boolean checkPermission(){
    int result = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION);
    if (result == PackageManager.PERMISSION_GRANTED){
        return true;
    } else {
        return false;
    }
}

private void requestPermission(){
    ActivityCompat.requestPermissions(activity,new String[]{
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CALL_PHONE},PERMISSION_REQUEST_CODE
    );
}

This code will check whether the version is above Lollipop OS. If so, then it will ask for permission to user while loading app.

Hope it will help you. Tested. Working properly.



来源:https://stackoverflow.com/questions/38305756/file-not-found-exception-when-reading-external-storage

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