listFiles() returns null on Android 6.0 emulator

前端 未结 3 1685
谎友^
谎友^ 2020-12-14 19:35

I want to read jpeg files from sdcard on Android 6.0 emulator, but file list returns null. The sample code can work on my phone:

            String sdcard =          


        
3条回答
  •  温柔的废话
    2020-12-14 20:42

    I have observed exactly the same problem, even after adding the runtime permissions code required with Android 6.0.

    In my activity I have the following code:

        int permissionCheck1 = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        int permissionCheck2 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionCheck1 != PackageManager.PERMISSION_GRANTED || permissionCheck2 != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                 Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_READWRITE_STORAGE);
        }
    

    and I receive the expected callback when the user confirms the request for the read/write storage permissions.

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions,
                                           int[] grantResults) {
        if (requestCode == REQUEST_READWRITE_STORAGE) {
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                finishCreationStep();
            }
        }
    }
    

    I have verified in the debugger that both the read and write permissions have been granted. Yet the subsequently executed call to read storage fails:

    File[] possible_files = mrpDir.listFiles();
    

    The call to listFiles() returns null. If I terminate the application, and go to Settings > Apps for my app, I see that the storage permission has been granted. If I also terminate the app, and then re-start it, the permissions are there, as expected, and the listFiles() calls works just fine. So, in other words, the change to permissions doesn't take effect until the app is terminated and re-started. Is there some way to get the app to recognize the changed permissions without having to make the user terminate and re-start it manually?

    As with the originator of this thread, I am running with an API 23 emulator, since I don't currently have access to an Android 6 device. So I suppose it's possible that there is a problem with the emulator. But that seems unlikely.

提交回复
热议问题