做Android开发都知道Google 老大哥 发出的诏令
自2019年8月1日起,已上架应用的更新,应基于Android 8.0 (API等级26)及以上开发,并拒绝API等级26以下的应用更新
(API等级26,即targetSdkVersion大于等于26)
然后基于Android 8.0的一些属性就会出现一些需要适配的工作
首先看报错的内容 也就是说 Android N对访问文件权限收回,按照Android N的要求,若要在应用间共享文件,您应发送一项 content://URI,并授予 URI 临时访问权限。而进行此授权的最简单方式是使用 FileProvider类。
那就一步一步去解决,是更改适配;
第一步
AndroidMainfest.xml文件中创建
<provider
android:name=".utill.MUpFileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/d_file_paths" />
</provider>
注意两点;1、 android:name=".utill.MUpFileProvider" , MUpFileProvider 类是我自定义的继承FileProvider ,为什么要自定义去继承,原因就是我其他地方有用到 FileProvider 这个类 ,我自定义会有冲突。2、 android:authorities="${applicationId}.provider" 网上好多写成android:authorities="自己报名.provider" 好像不能这么写 依然会报错 至少写成 android:authorities="${applicationId}.provider" 这样没报错
第二步
下载成功后自动安装更改
过时的方式:DownloadManager.COLUMN_LOCAL_FILENAME
Android 7.0以上的方式:请求获取写入权限,这一步报错 如果不按照Google 规定去写就直接报错,直接不兼容以前的代码了,这估计也是Google强行要求适配的原因吧。
做了个版本判断再进行自动去安装
Intent intent =new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri =FileProvider.getUriForFile(context.getApplicationContext(), BuildConfig.APPLICATION_ID +".provider", new File(filename));
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
}else {
intent.setDataAndType(Uri.fromFile(new File(filename)), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);