2

I've been bringing up the list of files in the folder as below, but I can't use the method below in Android Q(Android 10) or higher.

How do I load a list of files in the MUSIC folder using MediaStore?

public void getFileListInFolder() {

    String path = Environment.getExternalStoragePublicDirectory(DIRECTORY_MUSIC);
    File directory = null;

    try {
        directory = new File(path);
        Log.i("debug","dir = " + directory);
    }
    catch (Exception e)
    {
        Log.i("debug","Uri e = " + e);
    }

    File[] files = directory.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isFile();
        }
    });

    if(files != null)
    {
        for (int i = 0; i < files.length; i++) {
            Log.i("debug", "FileName:" + files[i].getName());
        }
    }
}
avs
  • 122
  • 1
  • 12
androidcho
  • 23
  • 5

1 Answers1

1

getExternalStoragePublicDirectory is deprecated since Android Q

To improve user privacy, direct access to shared/external storage devices is deprecated. When an app targets {@link android.os.Build.VERSION_CODES#Q}, the path returned from this method is no longer directly accessible to apps. Apps can continue to access content stored on shared/external storage by migrating to alternatives such as {@link Context#getExternalFilesDir(String)}, {@link MediaStore}, or {@link Intent#ACTION_OPEN_DOCUMENT}.

That means could not read/write file of /storage/emulated/0/Music directly, but could read/write file under /storage/emulated/0/Android/data/com.youapp/files/Music

public void getFileListInFolder() {
    String path = getExternalFilesDir(DIRECTORY_MUSIC).getAbsolutePath();
    Log.d(TAG, "getFileListInFolder:path " + path);
    File directory = null;
    try {
        directory = new File(path);
        Log.i(TAG,"dir = " + directory);
    }
    catch (Exception e)
    {
        Log.i(TAG,"Uri e = " + e);
    }
    File[] files = directory.listFiles();
    Log.i(TAG, "getFileListInFolder:files " + files);
    for (File f:
         files) {
        Log.d(TAG, "getFileListInFolder: " + f.getName());
    }
    if(files != null)
    {
        for (int i = 0; i < files.length; i++) {
            Log.i(TAG, "FileName:" + files[i].getName());
        }
    }
}
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108