Android 11 / API 30 访问 Android/data 和 media 目录以列出文件

Android 11 / API 30 Access Android/data and media Directory to list files

我在访问 Android/media 或 Android/data 目录时遇到了一些问题,今天我找到了解决方案,您可以在下面查看。 是的,我知道不建议在主线程中加载很多位图,这只是为了测试。

希望我能帮到你。

String stringWA = "primary:Android/media/com.whatsapp/WhatsApp/Media/.Statuses/";

LinearLayout ll;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    
    ll = findViewById(R.id.ll_add);

    Button btn = findViewById(R.id.button);
    btn.setOnClickListener(v -> {

        openDirectory();
    });



}
public void openDirectory() {

    // Choose a directory using the system's file picker.
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);

    // Optionally, specify a URI for the directory that should be opened in
    // the system file picker when it loads.


    startActivityForResult(intent.putExtra("android.provider.extra.INITIAL_URI", (Parcelable)DocumentsContract.buildDocumentUri((String)"com.android.externalstorage.documents", (String)stringWA)), 1234);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    super.onActivityResult(requestCode, resultCode, resultData);

    if (requestCode == 1234 && resultCode == Activity.RESULT_OK) {
        // The result data contains a URI for the document or directory that
        // the user selected.
        Uri uri = null;
        if (resultData != null) {
            uri = resultData.getData();
            try{
                loadImageIntoView(uri);
            }catch (Exception e){

            }

        }
    }
}
private void loadImageIntoView(Uri uri)  {
    DocumentFile dir = DocumentFile.fromTreeUri(this, uri);
    DocumentFile[] fileListed = dir.listFiles();

    for(int i = 0;i < fileListed.length;i++){
        ImageView iv = new ImageView(this);
        iv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
        try{
            InputStream is = getContentResolver().openInputStream(fileListed[i].getUri());
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            is.close();
            iv.setImageBitmap(bitmap);
        }catch (Exception e){
            iv.setImageResource(R.drawable.ic_baseline_error_24);
        }
        ll.addView(iv);

    }
}