美文网首页
android调用系统选取文件,解析真实路径,再用选择第三方ap

android调用系统选取文件,解析真实路径,再用选择第三方ap

作者: sunny635533 | 来源:发表于2022-04-22 11:00 被阅读0次

    android调用系统选取文件,解析真实路径,再用选择第三方app打开各类文件。涉及到知识点有几个,这几天终于搞懂了,感谢网上大家的分享,自己需要总结下。
    参考文章:
    1、选取文件后的路径解析:https://www.jianshu.com/p/d53243528917
    2、android手机路径的了解:https://www.jianshu.com/p/37448649244f
    3、Android FileProvider 详解: https://blog.csdn.net/yingaizhu/article/details/118972148
    4、打开各种格式的文件:https://blog.51cto.com/u_14397532/4930925

    具体代码实现如下:
    首先申请外部存储的读写权限:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    

    一、调用系统文件选择器来选择文件

    lateinit var fileChoose: ActivityResultLauncher<String>;
       var curFilePath: String? = null
    
       override fun onCreate(savedInstanceState: Bundle?) {
           super.onCreate(savedInstanceState)
           setContentView(R.layout.activity_main)
    
           val button = findViewById<Button>(R.id.btn)
           button.setOnClickListener { selectFile() }
           val openBtn = findViewById<Button>(R.id.openBtn)
           openBtn.setOnClickListener {
               openFile()
           }
           fileChoose = registerForActivityResult(GetContent()) { result ->
               try {
                   //content://com.android.providers.media.documents /document/image%3A335
                   //content://com.android.providers.downloads.documents /document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2FBrowser%2Fcom.apple.movetoios-3.2.6-universal-release.apk
                   //content://com.meizu.media.gallery.store /external/images/media/69
                   //content://com.android.providers.media.documents /document/video%3A41
                   //content://com.android.providers.downloads.documents /document/7
    
    //                println("========= =====result=>$result")
    //                println("========= =====path=>${result.path}  host=>${result.host}  scheme=>${result.scheme}")
                   findViewById<TextView>(R.id.text).text = result.path
    
                   var path = GetFilePathFromUri.getFileAbsolutePath(this@MainActivity, result)
                   findViewById<TextView>(R.id.abPath).text = path
                   curFilePath = path
               } catch (e: Exception) {
                   println(e.printStackTrace())
               }
    
           }
       }
    
       private fun selectFile() {
    //        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    //        intent.setType("*/*"); //无类型限制
    //        intent.addCategory(Intent.CATEGORY_OPENABLE);
           fileChoose.launch("*/*")
       }
    

    registerForActivityResult需要在onCreate方法初始化,不然会报错的。

    二、根据返回的content://XXXXX.XX路径,获取文件绝对路径,每个手机版本都不一样,分隔线是android4.4、10,

    public class GetFilePathFromUri {
    
        /**
         * 文件路径名称
         */
        public static String dirPathName = "appFiles";
    
        /**
         * 判断手机的外部存储是否有,如果没有就用内部存储
         *
         * @param context
         * @param dir
         * @return
         */
        public static String getFileDirPath(Context context, String dir) {
            String directoryPath = "";
            if (MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {//判断外部存储是否可用
                directoryPath = context.getExternalFilesDir(dir).getAbsolutePath();
            } else {//没外部存储就使用内部存储
                directoryPath = context.getFilesDir() + File.separator + dir;
            }
            File file = new File(directoryPath);
            if (!file.exists()) {//判断文件目录是否存在
                file.mkdirs();
            }
            return directoryPath;
        }
    
        /**
         * 根据Uri获取文件绝对路径,解决Android4.4以上版本Uri转换 兼容Android 10
         *
         * @param context
         * @param imageUri
         */
        public static String getFileAbsolutePath(Context context, Uri imageUri) {
            if (context == null || imageUri == null) {
                return null;
            }
    
            //4.4以下的版本
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
                return getRealFilePath(context, imageUri);
            } else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT
                    && android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
                    && DocumentsContract.isDocumentUri(context, imageUri)) {//大于4.4,小于10
                if (isExternalStorageDocument(imageUri)) {
                    String docId = DocumentsContract.getDocumentId(imageUri);
                    String[] split = docId.split(":");
                    String type = split[0];
                    if ("primary".equalsIgnoreCase(type)) {
                        return Environment.getExternalStorageDirectory() + "/" + split[1];
                    }
                } else if (isDownloadsDocument(imageUri)) {
                    String id = DocumentsContract.getDocumentId(imageUri);
                    if (!TextUtils.isEmpty(id)) {
                        if (id.startsWith("raw:")) {//已经返回真实路径
                            return id.replaceFirst("raw:", "");
                        }
                    }
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                    return getDataColumn(context, contentUri, null, null);
                } else if (isMediaDocument(imageUri)) {
                    String docId = DocumentsContract.getDocumentId(imageUri);
                    String[] split = docId.split(":");
                    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;
                    }
                    String selection = MediaStore.Images.Media._ID + "=?";
                    String[] selectionArgs = new String[]{split[1]};
                    return getDataColumn(context, contentUri, selection, selectionArgs);
                }
            } else if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {// MediaStore (and general)  大于等于10
                return uriToFileApiQ(context, imageUri);
            } else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
                // Return the remote address
                if (isGooglePhotosUri(imageUri)) {
                    return imageUri.getLastPathSegment();
                }
                if (Build.VERSION.SDK_INT >= 24) {
                    return getFilePathFromUri(context, imageUri); //content 类型
                } else {
                    return getDataColumn(context, imageUri, null, null);
                }
            }
            // File
            else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
                return imageUri.getPath();
            }
            return null;
        }
    
        private static String getRealFilePath(final Context context, final Uri uri) {
            if (null == uri) {
                return null;
            }
            final String scheme = uri.getScheme();
            String data = null;
            if (scheme == null) {
                data = uri.getPath();
            } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
                data = uri.getPath();
            } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
                String[] projection = {MediaStore.Images.ImageColumns.DATA};
                Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
                if (null != cursor) {
                    if (cursor.moveToFirst()) {
                        int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                        if (index > -1) {
                            data = cursor.getString(index);
                        }
                    }
                    cursor.close();
                }
            }
            return data;
        }
    
    
        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is ExternalStorageProvider.
         */
        private 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.
         */
        private static boolean isDownloadsDocument(Uri uri) {
            return "com.android.providers.downloads.documents".equals(uri.getAuthority());
        }
    
        private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
            Cursor cursor = null;
            String column = MediaStore.Images.Media.DATA;
            String[] projection = {column};
            try {
                cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
                if (cursor != null && cursor.moveToFirst()) {
                    int index = cursor.getColumnIndexOrThrow(column);
                    return cursor.getString(index);
                }
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
            return null;
        }
    
        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is MediaProvider.
         */
        private static boolean isMediaDocument(Uri uri) {
            return "com.android.providers.media.documents".equals(uri.getAuthority());
        }
    
        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is Google Photos.
         */
        private static boolean isGooglePhotosUri(Uri uri) {
            return "com.google.android.apps.photos.content".equals(uri.getAuthority());
        }
    
    
        /**
         * Android 10 以上适配 另一种写法
         *
         * @param context
         * @param uri
         * @return
         */
        @SuppressLint("Range")
        private static String getFileFromContentUri(Context context, Uri uri) {
            if (uri == null) {
                return null;
            }
            String filePath;
            String[] filePathColumn = {MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME};
            ContentResolver contentResolver = context.getContentResolver();
            Cursor cursor = contentResolver.query(uri, filePathColumn, null,
                    null, null);
            if (cursor != null) {
                cursor.moveToFirst();
                try {
                    filePath = cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
                    return filePath;
                } catch (Exception e) {
                } finally {
                    cursor.close();
                }
            }
            return "";
        }
    
        /**
         * Android 10 以上适配
         *
         * @param context
         * @param uri
         * @return
         */
        @RequiresApi(api = Build.VERSION_CODES.Q)
        private static String uriToFileApiQ(Context context, Uri uri) {
            File file = null;
            //android10以上转换
            if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
                file = new File(uri.getPath());
            } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
                //把文件复制到沙盒目录
                ContentResolver contentResolver = context.getContentResolver();
                Cursor cursor = contentResolver.query(uri, null, null, null, null);
                if (cursor.moveToFirst()) {
                    @SuppressLint("Range")
                    String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                    try {
                        InputStream is = contentResolver.openInputStream(uri);
    //                    File file1 = new File(context.getExternalCacheDir().getAbsolutePath()+"/"+System.currentTimeMillis());
    //                    if (!file1.exists()) {
    //                        file1.mkdir();
    //                    }
                        String dirPath = getFileDirPath(context, dirPathName);
                        File cache = new File(dirPath, displayName);
                        FileOutputStream fos = new FileOutputStream(cache);
                        FileUtils.copy(is, fos);
                        file = cache;
                        fos.close();
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return file.getAbsolutePath();
        }
    
        private static String getFilePathFromUri(Context context, Uri uri) {
            String realFilePath = getRealFilePath(context, uri); //防止获取不到真实的地址,因此这里需要进行判断
            if (!TextUtils.isEmpty(realFilePath)) {
                return realFilePath;
            }
    //        File filesDir = context.getApplicationContext().getFilesDir();
            String filesDir = getFileDirPath(context,dirPathName);
            String fileName = getFileName(uri);
            if (!TextUtils.isEmpty(fileName)) {
                File copyFile1 = new File(filesDir + File.separator + fileName);
                copyFile(context, uri, copyFile1);
                return copyFile1.getAbsolutePath();
            }
            return null;
        }
    
        private static String getFileName(Uri uri) {
            if (uri == null) {
                return null;
            }
            String fileName = null;
            String path = uri.getPath();
            int cut = path.lastIndexOf('/');
            if (cut != -1) {
                fileName = path.substring(cut + 1);
            }
            return fileName;
        }
    
        private static void copyFile(Context context, Uri srcUri, File dstFile) {
            try {
                InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
                if (inputStream == null) {
                    return;
                }
                OutputStream outputStream = new FileOutputStream(dstFile);
                copyStream(inputStream, outputStream);
                inputStream.close();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    
        private static int copyStream(InputStream input, OutputStream output) {
            final int BUFFER_SIZE = 1024 * 2;
            byte[] buffer = new byte[BUFFER_SIZE];
            BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
            BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE);
            int count = 0, n = 0;
            try {
                while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
                    out.write(buffer, 0, n);
                    count += n;
                }
                out.flush();
            } catch (Exception e) {
            } finally {
                try {
                    out.close();
                    in.close();
                } catch (Exception e) {
                }
            }
            return count;
        }
    
    }
    

    三、根据文件的绝对路径,用手机自带的第三方app预览文件,android7.0及以上的需要用fileProvider,否则无法打开。
    声明fileProvider在AndroidManifest.xml的application标签内

    <provider
                android:name="androidx.core.content.FileProvider"
                android:authorities="${applicationId}"
                android:exported="false"
                android:grantUriPermissions="true">
                <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/file_paths_public" />
            </provider>
    

    在res目录新建xml资源文件夹,创建file_paths_public.xml,

    <?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
        <!--1、对应内部内存卡根目录:Context.getFileDir()-->
        <files-path
            name="int_root"
            path="." />
        <!--2、对应应用默认缓存根目录:Context.getCacheDir()-->
        <cache-path
            name="app_cache"
            path="." />
        <!--3、对应外部内存卡根目录:Environment.getExternalStorageDirectory()-->
        <external-path
            name="ext_root"
            path="." />
        <!--4、对应外部内存卡根目录下的APP公共目录:Context.getExternalFileDir(String)-->
        <external-files-path
            name="ext_pub"
            path="." />
        <!--5、对应外部内存卡根目录下的APP缓存目录:Context.getExternalCacheDir()-->
        <external-cache-path
            name="ext_cache"
            path="." />
    </paths>
    

    最后一步打开该文件,把file路径转成content://XXXX/XX的uri,

    fun openFile(){
            try{
                var intent = Intent("android.intent.action.VIEW");
                intent.addCategory("android.intent.category.DEFAULT");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                var uri: Uri;
                var file:File
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {// 7.0及以上,需要用到provider
                    file = File("$curFilePath")
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)//FLAG_GRANT_WRITE_URI_PERMISSION
                    uri = FileProvider.getUriForFile(this@MainActivity, "com.org.filechooseapp", file)
                    //使用fileProvider后,选择android10手机的某个文件,file路径转成content,如下:content://com.org.filechooseapp/ext_pub/appFiles/fd_tmp_file.txt
                } else {
                    file = File("file://$curFilePath")
                    uri = Uri.fromFile(file)
                }
                intent.setDataAndType(uri, getMIMEType(file))
                this.startActivity(intent)
            }catch (e:Exception){
                e.printStackTrace()
                Toast.makeText(this@MainActivity,"文件打开失败",Toast.LENGTH_LONG).show()
            }
        }
    
    
        /* 判断文件MimeType的method */
        fun getMIMEType(f: File): String {
            var type: String = ""
            var fName: String = f.name
            /* 取得扩展名 */
            var end:String = fName.substring (fName.lastIndexOf(".") + 1, fName.length).lowercase(Locale.getDefault());
    
            /* 按扩展名的类型决定MimeType */
            if (end == "m4a" || end == "mp3" || end == "mid" || end == "xmf" || end == "ogg" || end == "wav" || end == "mpga") {
                return "audio/*";
            } else if (end == "3gp" || end == "mp4" || end == "mpg4" || end == "mov") {
                return "video/*";
            } else if (end == "jpg" || end == "gif" || end == "png" || end == "jpeg" || end == "bmp") {
                return "image/*";
            } else if(end == "txt" || end == "log" || end == "xml"){
                return "text/plain"
            } else if(end == "pdf"){
                return "application/pdf"
            }else if(end == "doc"){
                return "application/msword"
            }else if(end == "docx"){
                return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            }else if(end == "xls"){
                return "application/vnd.ms-excel"
            }else if(end == "xlsx"){
                return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            }else if(end == "exe"){
                return "application/octet-stream"
            } else if(end == "ppt"){
                return "application/vnd.ms-powerpoint"
            }else if(end == "pptx"){
                return "application/vnd.openxmlformats-officedocument.presentationml.presentation"
            }else if(end == "tar"){
                return "application/x-tar"
            }else if(end == "tgz"){
                return "application/x-compressed"
            }else if(end == "zip"){
                return "application/x-zip-compressed"
            }
            else if (end == "apk") {
                /* android.permission.INSTALL_PACKAGES */
                //用下载并自动安装apk包
                return "application/vnd.android.package-archive"
            } else {
                /* 如果无法直接打开,就弹出软件列表给用户选择 */
               return "*/*"
            }
        }
    
    //    private final String[][] MIME_MapTable={
    ////{后缀名,MIME类型}
    //        {".3gp", "video/3gpp"},
    //        {".apk", "application/vnd.android.package-archive"},
    //        {".asf", "video/x-ms-asf"},
    //        {".avi", "video/x-msvideo"},
    //        {".bin", "application/octet-stream"},
    //        {".bmp", "image/bmp"},
    //        {".c", "text/plain"},
    //        {".class", "application/octet-stream"},
    //        {".conf", "text/plain"},
    //        {".cpp", "text/plain"},
    //        {".doc", "application/msword"},
    //        {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    //        {".xls", "application/vnd.ms-excel"},
    //        {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    //        {".exe", "application/octet-stream"},
    //        {".gif", "image/gif"},
    //        {".gtar", "application/x-gtar"},
    //        {".gz", "application/x-gzip"},
    //        {".h", "text/plain"},
    //        {".htm", "text/html"},
    //        {".html", "text/html"},
    //        {".jar", "application/java-archive"},
    //        {".java", "text/plain"},
    //        {".jpeg", "image/jpeg"},
    //        {".jpg", "image/jpeg"},
    //        {".js", "application/x-javascript"},
    //        {".log", "text/plain"},
    //        {".m3u", "audio/x-mpegurl"},
    //        {".m4a", "audio/mp4a-latm"},
    //        {".m4b", "audio/mp4a-latm"},
    //        {".m4p", "audio/mp4a-latm"},
    //        {".m4u", "video/vnd.mpegurl"},
    //        {".m4v", "video/x-m4v"},
    //        {".mov", "video/quicktime"},
    //        {".mp2", "audio/x-mpeg"},
    //        {".mp3", "audio/x-mpeg"},
    //        {".mp4", "video/mp4"},
    //        {".mpc", "application/vnd.mpohun.certificate"},
    //        {".mpe", "video/mpeg"},
    //        {".mpeg", "video/mpeg"},
    //        {".mpg", "video/mpeg"},
    //        {".mpg4", "video/mp4"},
    //        {".mpga", "audio/mpeg"},
    //        {".msg", "application/vnd.ms-outlook"},
    //        {".ogg", "audio/ogg"},
    //        {".pdf", "application/pdf"},
    //        {".png", "image/png"},
    //        {".pps", "application/vnd.ms-powerpoint"},
    //        {".ppt", "application/vnd.ms-powerpoint"},
    //        {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    //        {".prop", "text/plain"},
    //        {".rc", "text/plain"},
    //        {".rmvb", "audio/x-pn-realaudio"},
    //        {".rtf", "application/rtf"},
    //        {".sh", "text/plain"},
    //        {".tar", "application/x-tar"},
    //        {".tgz", "application/x-compressed"},
    //        {".txt", "text/plain"},
    //        {".wav", "audio/x-wav"},
    //        {".wma", "audio/x-ms-wma"},
    //        {".wmv", "audio/x-ms-wmv"},
    //        {".wps", "application/vnd.ms-works"},
    //        {".xml", "text/plain"},
    //        {".z", "application/x-compress"},
    //        {".zip", "application/x-zip-compressed"},
    //        {"", "*/*"}
    //    };
    

    相关文章

      网友评论

          本文标题:android调用系统选取文件,解析真实路径,再用选择第三方ap

          本文链接:https://www.haomeiwen.com/subject/rtngertx.html