解决思路:在Android12中调用文件管理器,尤其在下载内容中,无法对个别的文件路径进行解析,出现返回路径为空的情况,解决办法就是对不同文件的uri进行分析,分情况进行判断并返回路径。
1.如果是下载内容中的文件,
(isDownloadsDocument(uri)) 在这里面对不同后缀的文件进行类型判断
else if (isDownloadsDocument(uri)) {
Log.d("ChooseFile", "uri: " + uri);
final String docId = DocumentsContract.getDocumentId(uri);
String id;
// 1.
if (docId != null && docId.startsWith("raw:")) {
Log.e("", "" + docId.substring(4));
return docId.substring(4);
}
//2.
Log.d("ChooseFile", "docId: " + docId);
if (docId.contains(":")) {
final String[] split = docId.split(":");
final String type = split[0];
id = split[1];
} else {
id = docId;
}
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
try {
path = getDataColumn(context, contentUri, null, null);
} catch (Exception e) {
;
}
//3.
if(path == null || path.isEmpty()) {
path = getFilePathForN(context, uri);
java.io.File filt = new java.io.File(path);
if (filt.exists() && filt.canRead())
Log.e("FileChoose", "final choose succeed");
}
return path;
/*
String fileName = getFileName(context, uri);
path = android.os.Environment.getExternalStorageDirectory() + "/Download/" + fileName;
Log.e("4.4以后-download-content_Path", path);
return path;
*/
}
2.如果在下载内容中,通过getDataColumn获得的path为空或者empty,那么可以将uri文件复制到
另外一个路径,重新获取文件路径
private static String getFilePathForN(Context context, Uri uri) {
try {
Cursor returnCursor = context.getContentResolver().query(uri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
//java.io.File file = new java.io.File(context.getFilesDir(), name);
java.io.File file = new java.io.File(GlobalInfo.dataTempDir, name);
InputStream inputStream = context.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
returnCursor.close();
inputStream.close();
outputStream.close();
return file.getPath();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
总结:完整的代码如下
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import com.example.abeclient.constant.GlobalInfo;
import java.io.FileOutputStream;
import java.io.InputStream;
public class ChooseFileUtil {
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @author paulburke
*/
public static String getPath(final Context context, final Uri uri) {
try {
String path = null;
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
Log.d("ChooseFile", "uri: " + uri);
final String docId = DocumentsContract.getDocumentId(uri);
String id;
// 1.
if (docId != null && docId.startsWith("raw:")) {
Log.e("", "" + docId.substring(4));
return docId.substring(4);
}
//2.
Log.d("ChooseFile", "docId: " + docId);
if (docId.contains(":")) {
final String[] split = docId.split(":");
final String type = split[0];
id = split[1];
} else {
id = docId;
}
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
try {
path = getDataColumn(context, contentUri, null, null);
} catch (Exception e) {
;
}
//3.
if(path == null || path.isEmpty()) {
path = getFilePathForN(context, uri);
java.io.File filt = new java.io.File(path);
if (filt.exists() && filt.canRead())
Log.e("FileChoose", "final choose succeed");
}
return path;
/*
String fileName = getFileName(context, uri);
path = android.os.Environment.getExternalStorageDirectory() + "/Download/" + fileName;
Log.e("4.4以后-download-content_Path", path);
return path;
*/
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
} else if ("document".equals(type)) {
contentUri = MediaStore.Files.getContentUri("external");
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static String getFileName(Context context, Uri uri)
{
Cursor cursor = null;
String[] projection = {
MediaStore.MediaColumns.DISPLAY_NAME
};
try
{
cursor = context.getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null && cursor.moveToFirst())
{
int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
//int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.OWNER_PACKAGE_NAME);
Log.e("index-fileDic", cursor.getString(index));
return cursor.getString(index);
}
}
finally
{
if (cursor != null)
if (cursor != null)
{
cursor.close();
}
}
return null;
}
private static String getFilePathForN(Context context, Uri uri) {
try {
Cursor returnCursor = context.getContentResolver().query(uri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
//java.io.File file = new java.io.File(context.getFilesDir(), name);
java.io.File file = new java.io.File(GlobalInfo.dataTempDir, name);
InputStream inputStream = context.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
returnCursor.close();
inputStream.close();
outputStream.close();
return file.getPath();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
参考链接:(1条消息) 2022-02-26 AndroidR 11 调用文件管理器并返回选中文件的路径_海月汐辰的博客-CSDN博客_android11文件管理