自从google发布必须适配Android8.0以来,小心肝都颤了颤,这回是真的有必要逼自己一把了,再也不能偷懒了,不开心。
之前为了方便把targetSdkVersion写成22以下,酱就少了权限的判断和文件uri的判断,但是现在都要统统补上了。
不过适配8.0还是有必要的。经过一番折腾,终于完成了向Android8.0的迁移,总结为以下几方面:
- Android studio更新
- 权限判断
- 文件uri判断
Android studio更新
作为一个没有Android8.0以上手机的程序媛而言,就要使用as的模拟器了,然而Android 8.0 系统映像只能通过 Android Studio 3.0 Canary 下载,好吧,只能先更新我的AS了。大概有以下几点注意:
- 修改gradle.properties
AAPT2 编译报错,AS3.0的aapt2默认情况下是打开的,关上就OK了。
在gradle.properties最后添加下行代码:
android.enableAapt2=false
- 修改项目下build.gradle
仓库位置调整到google,需要在配置仓库的地方加入google()
allprojects {
repositories {
jcenter()
mavenCentral()
maven { url 'https://jitpack.io' }
google()
}
}
- 修改app下build.gradle
compileSdkVersion 26
buildToolsVersion '26.0.2'
然后坐等AS更新成功
权限判断
网上有很多权限判断的三方库,推荐一个较好用的:
https://github.com/googlesamples/easypermissions
用法就自己看吧,还是比较简单的
文件权限更改
为了提高私有文件的安全性,面向 Android 7.0 或更高版本的应用私有目录被限制访问,因此,问题出来了,常见的下载更新和拍照就会出现FileUriExposedException错误,具体详见:https://developer.android.google.cn/about/versions/nougat/android-7.0-changes.html
要在应用间共享文件,您应发送一项 content:// URI,并授予 URI 临时访问权限。进行此授权的最简单方式是使用 FileProvider 类。
其实很简单了,修改以下:
1,清单文件application下添加:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="自己的包名.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,在xml中新建文件file_paths:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="files_root"
path="Android/data/自己的包名/" />
<external-path
name="external_storage_root"
path="." />
</paths>
3.使用
//下载成功,覆盖原来的apk
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri uri = FileProvider.getUriForFile(mContext,
BuildConfig.APPLICATION_ID + ".fileprovider", file);
intent.setDataAndType(uri,
"application/vnd.android.package-archive");
} else {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(response.body()),
"application/vnd.android.package-archive");
}
mContext.startActivity(intent);
然后就算成功开始8.0开发了。