您可以使用以下代码示例来在Android中使用ACTION_GET_CONTENT意图检索文件:
private static final int PICK_FILE_REQUEST_CODE = 1;
private void pickFile() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*"); // 选择所有类型的文件
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent, "选择文件"), PICK_FILE_REQUEST_CODE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "请安装文件管理器", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FILE_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
Uri uri = data.getData();
// 使用uri获取文件路径
String filePath = getPathFromUri(uri);
// TODO: 处理文件路径
}
}
private String getPathFromUri(Uri uri) {
String path = null;
if (DocumentsContract.isDocumentUri(this, uri)) {
// 如果是Document类型的Uri,则使用Document ID来检索路径
String documentId = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
path = getDataColumn(contentUri, null, null);
} else if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
String id = documentId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=" + id;
path = getDataColumn(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
// 如果是Content类型的Uri,则使用ContentResolver来检索路径
path = getDataColumn(uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
// 如果是File类型的Uri,则直接返回文件路径
path = uri.getPath();
}
return path;
}
private String getDataColumn(Uri uri, String selection, String[] selectionArgs) {
String path = null;
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.moveToFirst()) {
path = cursor.getString(columnIndex);
}
cursor.close();
}
return path;
}
上述代码中,pickFile()方法用于启动ACTION_GET_CONTENT意图,使用Intent.createChooser()方法来显示文件选择器。onActivityResult()方法用于处理返回的结果,从URI中获取文件路径。getPathFromUri()方法根据不同的Uri类型来检索路径,使用ContentResolver来查询Content类型的Uri,并使用MediaStore来查询Document类型的Uri。getDataColumn()方法用于从Cursor中获取路径。