项目targetVersion升级到28遇到的一些小坑及其解决
迁移AndroidX
AndroidX概述
gradle.properties加上两个插件标记
- 确保你的AS在3.2版本或3.2之上;
- compileSdkVersion 至少28(android 9.0);
- 在gradle.properties中设置"android.useAndroidX=true",
“android.enableJetifier=true”
(useAndroidX:是否使用androidX的库,false时使用support库。
enableJetifier:是否让第三方库也自动使用androidX) - 菜单栏选择Refactor > Migrate to AndroidX
org.gradle.jvmargs=-Xmx8704m
android.useAndroidX=true
android.enableJetifier=true
说明:
- android.useAndroidX:如果设置为 true,Android 插件会使用相应的 AndroidX 库,而非支持库。如果未指定,则该标记默认为 false。
- android.enableJetifier:如果设置为 true,Android 插件会重写其二进制文件,自动迁移现有的第三方库以使用 AndroidX。如果未指定,则该标记默认为 false。
报错
java.lang.IllegalStateException: Not allowed to start service Intent { act=xxx cmp=xxx}: app is in background uid UidRecord{xxxx}
分析
Android 8.0 对应用在用户不与其直接交互时可以执行的操作施加了限制后台执行限制
解决方案:
用startForegroundService()方法启动服务
//8.0以后启动service适配
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
activity.startForegroundService(new Intent(MyActivity.this, MyService.class));
}else{
activity.startService(new Intent(MyActivity.this, MyService.class));
}
在service的onCreate()方法里调用startForeground()方法
NotificationChannel mChannel = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Notification notification = new Notification.Builder(getApplicationContext(), "my_service0").build();
startForeground(1, notification);
}
报错
W/System.err: java.io.IOException: Cleartext HTTP traffic to **** not permitted
分析
解决方案
-
改用https请求
-
targetVersion降低到27以下(我就是升到28的,不降,o(∩_∩)o )
-
在res下新增一个xml目录,新建一个xml文件:network_security_config.xml,修改base-config cleartextTrafficPermitted的值(默认为false)
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true" /> </network-security-config>
然后在manifest的application节点加android:networkSecurityConfig
<application ... android:networkSecurityConfig="@xml/network_security_config" ... />
报错
java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
分析
在manifest定义的activty是半透明的,加了screenOrientation属性
解决方法
去掉screenOrientation即可
问题
notification没有显示
targetVersion26及以上开始要求notification必须知道channel,具体查阅Create and Manage Notification Channels
解决方法
在notify之前先创建notificationChannel
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(“channel_id”,
"channel_name",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
问题
分析
解决
1、把targetVersion设置为28以下(本来就是升级,⊙﹏⊙‖∣)
2、在application节点下加入
<application/>
<uses-library
android:name="org.apache.http.legacy"
android:required="false"/>
</application>