记录targetSdkVersion升级以后Android遇到的一些问题

Android7.0以后的文件读取

Android7.0以后通过FileProvider在应用间共享文件

步骤1:在res的文件夹下建立一个xml的文件夹,再建立一个provider_paths.xml,
provider_path.xm的内容如下:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external" path="."/>
</paths>

步骤2:在AndroidManifest.xml中配置信息:

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.example" //最好是你的包名
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths" />
</provider>

使用

File file = new File(Environment
        .getExternalStorageDirectory(), "image.jpg");
if(Build.VERSION.SDK_INT>=24) { //判读版本是否在7.0以上
 	//参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
	tempUri =FileProvider.getUriForFile(context, "com.example", file);
	//添加这一句表示对目标应用临时授权该Uri所代表的文件
}else{
    tempUri = Uri.fromFile(file);
}

Android 8.0 后台不能开启服务问题

遇到的报错内容如下:

java.lang.IllegalStateException: Not allowed to start service Intent { flg=0x10000000 cmp=XXXX }: app is in background uid UidRecord{9327d82 u0a489 RCVR bg:+5m35s828ms idle change:uncached 

解决方案:
startService 改为

if (Build.VERSION.SDK_INT >= 26) {
    context.startForegroundService(intent);
} else {
    context.startService(intent);
}

Context.startForegroundService() 函数将启动一个前台服务。现在,即使应用在后台运行,系统也允许其调用
Context.startForegroundService()。不过,应用必须在创建服务后的五秒内调用该服务的
startForeground() 函数。

所以需要在启动的service的onStartCommand中,调用

startForeground(2, new Notification());

Android9.0 http解决方案

方案1 简单粗暴

步骤1:在 res 下新建一个 xml 目录,然后创建一个名为:network_security_config.xml 文件 ,该文件内容如下:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

步骤2:在 AndroidManifest.xml application 标签内应用上面的xml配置:
android:networkSecurityConfig="@xml/network_security_config" 如下:

<application>
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:theme="@style/AppTheme">
</application>
方案2 降级targetSdkVersion 到27

你可能感兴趣的:(android)