• Android 打开系统文件管理器,并返回选中文件的路径


    职场小白迷上优美句子: 

    推迟,拖延真的是件可怕的事,过去了好久还是原来的样子。

    公司现在的项目中有一个需求,需要把本地 json 格式的数据导入到项目中使用,其实简单的逻辑就是:使用安卓隐式跳转的方式进入到文件管理器,然后寻找需要的文件,点击文件之后返回该文件的路径,之后根据路径获取到该文件并对其进行相应的操作。

    这些代码不是自己在Android 官网上找的,也是从百度搜的,当然需要标明出处:

    Android调用系统自带的文件管理器,打开指定路径_android file 内置文件到机器特定路径_沧海龙腾LV的博客-CSDN博客

    1.进入文件管理器

    1. private void intoFileManager() {
    2. Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    3. intent.setType("*/*");//无类型限制
    4. // 有类型限制是这样的:
    5. // intent.setType(“image/*”);//选择图片
    6. //        intent.setType(“audio/*”); //选择音频
    7. //        intent.setType(“video/*”); //选择视频 (mp4 3gp 是android支持的视频格式)
    8. //        intent.setType(“video/*;image/*”);//同时选择视频和图片
    9. intent.addCategory(Intent.CATEGORY_OPENABLE);
    10. startActivityForResult(intent, 1);
    11. }

    2.返回结果

    1. String path;
    2. @Override
    3. protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    4. super.onActivityResult(requestCode, resultCode, data);
    5. if (resultCode == Activity.RESULT_OK) {
    6. Uri uri = data.getData();
    7. if ("file".equalsIgnoreCase(uri.getScheme())){//使用第三方应用打开
    8. path = uri.getPath();
    9. mFilePathTv.setText(path);
    10. Log.d("queryfilepath", "返回结果1: " + path);
    11. return;
    12. }
    13. if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
    14. path = FileChooseUtil.getPath(this, uri);
    15. mFilePathTv.setText(path);
    16. Log.d("queryfilepath", "返回结果2: " + path);
    17. } else {//4.4以下下系统调用方法
    18. path = FileChooseUtil.getRealPathFromURI(uri);
    19. mFilePathTv.setText(path);
    20. Log.d("queryfilepath", "返回结果3: " + path);
    21. }
    22. }
    23. }

    3.用到的工具类

    1. public class FileChooseUtil {
    2. private static Context context;
    3. private static FileChooseUtil util = null;
    4. private FileChooseUtil(Context context) {
    5. this.context = context;
    6. }
    7. public static FileChooseUtil getInstance(Context context) {
    8. if (util == null) {
    9. util = new FileChooseUtil(context);
    10. }
    11. return util;
    12. }
    13. /**
    14. * 对外接口 获取uri对应的路径
    15. *
    16. * @param uri
    17. * @return
    18. */
    19. public String getChooseFileResultPath(Uri uri) {
    20. String chooseFilePath = null;
    21. if ("file".equalsIgnoreCase(uri.getScheme())) {//使用第三方应用打开
    22. chooseFilePath = uri.getPath();
    23. Toast.makeText(context, chooseFilePath, Toast.LENGTH_SHORT).show();
    24. return chooseFilePath;
    25. }
    26. if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
    27. chooseFilePath = getPath(context, uri);
    28. } else {//4.4以下下系统调用方法
    29. chooseFilePath = getRealPathFromURI(uri);
    30. }
    31. return chooseFilePath;
    32. }
    33. public static String getRealPathFromURI(Uri contentUri) {
    34. String res = null;
    35. String[] proj = {MediaStore.Images.Media.DATA};
    36. Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
    37. if (null != cursor && cursor.moveToFirst()) {
    38. int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    39. res = cursor.getString(column_index);
    40. cursor.close();
    41. }
    42. return res;
    43. }
    44. /**
    45. * 专为Android4.4设计的从Uri获取文件绝对路径,以前的方法已不好使
    46. */
    47. @SuppressLint("NewApi")
    48. public static String getPath(final Context context, final Uri uri) {
    49. final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    50. // DocumentProvider
    51. if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
    52. // ExternalStorageProvider
    53. if (isExternalStorageDocument(uri)) {
    54. final String docId = DocumentsContract.getDocumentId(uri);
    55. final String[] split = docId.split(":");
    56. final String type = split[0];
    57. if ("primary".equalsIgnoreCase(type)) {
    58. return Environment.getExternalStorageDirectory() + "/" + split[1];
    59. }
    60. }
    61. // DownloadsProvider
    62. else if (isDownloadsDocument(uri)) {
    63. final String id = DocumentsContract.getDocumentId(uri);
    64. final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
    65. return getDataColumn(context, contentUri, null, null);
    66. }
    67. // MediaProvider
    68. else if (isMediaDocument(uri)) {
    69. final String docId = DocumentsContract.getDocumentId(uri);
    70. final String[] split = docId.split(":");
    71. final String type = split[0];
    72. Uri contentUri = null;
    73. if ("image".equals(type)) {
    74. contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    75. } else if ("video".equals(type)) {
    76. contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
    77. } else if ("audio".equals(type)) {
    78. contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    79. }
    80. final String selection = "_id=?";
    81. final String[] selectionArgs = new String[]{split[1]};
    82. return getDataColumn(context, contentUri, selection, selectionArgs);
    83. }
    84. }
    85. // MediaStore (and general)
    86. else if ("content".equalsIgnoreCase(uri.getScheme())) {
    87. return getDataColumn(context, uri, null, null);
    88. }
    89. // File
    90. else if ("file".equalsIgnoreCase(uri.getScheme())) {
    91. uri.getPath();
    92. }
    93. return null;
    94. }
    95. private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
    96. Cursor cursor = null;
    97. final String column = "_data";
    98. final String[] projection = {column};
    99. try {
    100. cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
    101. null);
    102. if (cursor != null && cursor.moveToFirst()) {
    103. final int column_index = cursor.getColumnIndexOrThrow(column);
    104. return cursor.getString(column_index);
    105. }
    106. } finally {
    107. if (cursor != null)
    108. cursor.close();
    109. }
    110. return null;
    111. }
    112. /**
    113. * @param uri The Uri to check.
    114. * @return Whether the Uri authority is ExternalStorageProvider.
    115. */
    116. private static boolean isExternalStorageDocument(Uri uri) {
    117. return "com.android.externalstorage.documents".equals(uri.getAuthority());
    118. }
    119. /**
    120. * @param uri The Uri to check.
    121. * @return Whether the Uri authority is DownloadsProvider.
    122. */
    123. private static boolean isDownloadsDocument(Uri uri) {
    124. return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    125. }
    126. /**
    127. * @param uri The Uri to check.
    128. * @return Whether the Uri authority is MediaProvider.
    129. */
    130. private static boolean isMediaDocument(Uri uri) {
    131. return "com.android.providers.media.documents".equals(uri.getAuthority());
    132. }
    133. }

    注意:记得开启手机的读写权限,不然会报权限拒绝异常:SecurityException ! !   !

  • 相关阅读:
    计算机毕业设计Java超市购物数据管理系统(源码+系统+mysql数据库+lw文档)
    antd——使用a-tree组件实现 检索+自动展开+自定义增删改查功能——技能提升
    基于 OPLG 从 0 到 1 构建统一可观测平台实践
    Ingress安全网关
    队列及其Java实现
    Nmap网络扫描
    Greenplum高可用-从失效segment恢复
    论文阅读之《Learn to see in the dark》
    linux网络编程
    构建创新增值能力优势,康铂酒店突围中端酒店市场!
  • 原文地址:https://blog.csdn.net/xiaowang_lj/article/details/133387294