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);
 
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值