问题:在Android Q 上使用第三方的打开文件的方式去分享文件,点击启动activity,intent并没发出去,也没有崩溃

Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		String type = DocumentUtils.getMIMEType(file);
		Uri uri;
	         uri = Uri.fromFile(file);
		intent.setDataAndType(uri, type);
		try {
			intent.setAction(Intent.ACTION_VIEW);
			intent.addCategory("android.intent.category.DEFAULT");
			Intent chooser = Intent.createChooser(intent, null);
			startActivity(chooser);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		}

没有崩溃的原因是因为在Android 7.0以上就不建议使用file:// URI分享文件 ,当时借鉴网上比较简单的方法去解决这个问题

  StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());

当时确实解决了不少问题,但是在Android 10上,文件还是不能分享,并且也不崩溃,问题找的好惨都要崩溃了,最后使用使用FileProvider的Content Uri替换File Uri,参考谷歌提供的适配指导链接:https://developer.android.com/training/secure-file-sharing

通过FileProvider分享大致的流程总结

1.清单文件中注册
 <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>
        </provider>
2. res/xml文件夹下新建 file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external" path="" />
</paths>
3.代码根据版本判断
Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		String type = DocumentUtils.getMIMEType(file);
		Uri uri;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//			 uri = FileProvider.getUriForFile(mContext, "app的包名.fileProvider", photoFile);
			uri = FileProvider.getUriForFile(
					mContext,
					mContext.getPackageName()+".fileprovider",
					file);
		} else {
			 uri = Uri.fromFile(file);
		}
		intent.setDataAndType(uri, type);
		try {
			intent.setAction(Intent.ACTION_VIEW);
			intent.addCategory("android.intent.category.DEFAULT");
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			Intent chooser = Intent.createChooser(intent, null);
			startActivity(chooser);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐