安卓11 获取文件路径

时间:2025-01-30 13:11:07

获取读写权限

1、清单文件中添加权限
<uses-permission android:name=".WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name=".READ_EXTERNAL_STORAGE" />
<uses-permission android:name=".MANAGE_EXTERNAL_STORAGE" />
2、请求动态权限
private void requestPermission(Context context){
	// 通过api判断手机当前版本号
	if (.SDK_INT >= Build.VERSION_CODES.R) {
		// 安卓11,判断有没有“所有文件访问权限”权限
		if (()) {
        	openFile();
		} else {
    		Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
        	(("package:" + ()));
        	startActivityForResult(intent, REQUEST_CODE);
        }
	} else if (.SDK_INT >= Build.VERSION_CODES.M) {
		// 安卓6 判断有没有读写权限权限
        if ((this, .READ_EXTERNAL_STORAGE) ==PackageManager.PERMISSION_GRANTED && (this, .WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
			openFile();
	} else {
    	(this, new String[]{.READ_EXTERNAL_STORAGE, .WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
        }
	} else {
    	openFile();
	}
}
	
	@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        (requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            if ((this, .READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    (this, .WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                openFile();
            } else {
                ("存储权限获取失败");
            }
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        (requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && .SDK_INT >= Build.VERSION_CODES.R) {
            if (()) {
                openFile();
            } else {
                ("存储权限获取失败");
            }
        }
    }

Uri获取文件路径

1、移动到文件管理器
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// 选择Excel文件, 我这项目选择Excel类型文件
("application/-excel");
startActivityForResult(intent, IMPORT_FILE_CODE);
2、获取选中文件的路径
	@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        (requestCode, resultCode, data);
        if (requestCode == IMPORT_FILE_CODE && resultCode == Activity.RESULT_OK){
            Uri uri = ();
            String path = (, uri);
        }
    }

	public String getPath(final Context context, final Uri uri) {
		if (.SDK_INT >= Build.VERSION_CODES.KITKAT && (context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = (uri);
                final String[] split = (":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return () + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = (uri);
                final Uri contentUri = (("content://downloads/public_downloads"), (id));
                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = (uri);
                final String[] split = (":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = .EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = .EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = .EXTERNAL_CONTENT_URI;
                }else {
                    contentUri = ("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(())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(())) {
            return ();
        }
        return null;
	}

	public String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = ().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && ()) {
                final int column_index = (column);
                return (column_index);
            }
        } catch (Exception e) {
            ();
        } finally {
            if (cursor != null) {
                ();
            }
        }
        return null;
    }
	
	/**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "".equals(());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "".equals(());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "".equals(());
    }