安卓应用使用系统或第三方应用打开文件预览

AndrodiManifest.xml文件中配置

<provider
            android:name="com.soonfor.repository.view.Mdgj_ZskFileProvider"
            android:authorities="com.soonfor.repository.mdgj_zffileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/rep_file_paths" />
 </provider>

之后在资源文件夹中创建
rep_file_paths.xml文件,文件内容如下

<paths>
    <external-path name="my_images" path="Pictures"/>
    <external-path name="UcpFiles" path="UcpFiles/" />
</paths>

设置完成以上步奏调用以下代码就可以打开了

Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(path)).toString());
        String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        //7.0以上需要
        if (Build.VERSION.SDK_INT >= 24) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(context, "com.soonfor.repository.mdgj_zffileprovider", new File(path));
            intent.setDataAndType(uri, mimetype);
        } else {
            intent.setDataAndType(Uri.fromFile(new File(path)), mimetype);
        }
        context.startActivity(intent);

猜你喜欢

转载自blog.csdn.net/sinat_24112081/article/details/103022546