AndroidX使用Intent打開文件

1. 創建FileProvider放在項目xml裏面

在這裏插入圖片描述

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">

    <!--    所有文件都有效-->
    <root-path
        name="root-path"
        path="" />
    <!--    指定路徑下的文件-->
    <external-path
        name="download"
        path="/glacier/house/download/" />

</paths>

2. 在AndroidManifest添加provider

  • 馬賽克部分填寫你的包名
    在這裏插入圖片描述
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${填寫包名}.fileprovider"
            android:exported="false"
            tools:replace="android:authorities"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                tools:replace="android:resource"
                android:resource="@xml/filepaths"
                />
        </provider>

3. 打開文件

    /**
     * 打開文件
     * @param filepath 文件完整路徑
     * @param context
     */
    public static void openAndroidFile(String filepath, Context context) {
        Intent handlerIntent = new Intent();
        File file = new File(filepath);
        handlerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //動作,查看
        handlerIntent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(file);
        String type = getMIMEType(file);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            handlerIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);

            handlerIntent.setDataAndType(uri, type);
            context.startActivity(handlerIntent);
        } else {
            handlerIntent.setDataAndType(uri, type);
            context.startActivity(handlerIntent);
        }
    }
// 系統提供的解析文件類型的方法
private static void openFile(Context context, File f) {
        Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
        String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(f).toString());
        String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        myIntent.setDataAndType(Uri.fromFile(f),mimetype);
        context.startActivity(myIntent);
 
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章