一、申请权限
需要申请权限读写外部文件,在Manifest文件中输入以下代码对权限进行声明,分别是读外部文件权限和写外部文件权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage" />
二、调用系统文件选择器
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);//筛选文件(这里是读取音频目录)intent.setType("audio/*");//调用系统文件选择器startActivityForResult(intent,100);
三、在Activity回调函数中接收Uri并处理
@Overrideprotected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {super.onActivityResult(requestCode, resultCode, data);if (resultCode == Activity.RESULT_OK && requestCode == 100) {//获取UriUri uri = data.getData();//根据Uri查询文件名Cursor cursor = ((Activity)context).getContentResolver().query(uri,null,null,null,null);if(cursor != null){int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);cursor.moveToFirst();//文件名String fileName = cursor.getString(nameIndex);cursor.close();System.out.println(fileName);}}}
运行效果:
直接复制就能用,没效果你来砍我
来源地址:https://blog.csdn.net/qq_41983414/article/details/130825636