兼容android10下载apk后无法安装问题

        android兼容问题比较多,不仅仅是各种型号手机的兼容,SDK版本升级也得兼容,这不,今天发布了一个APK,android 9以下手机能在线下载最新APK后能安装,android 10就不行了,网上查阅一下资料,因为android权限控制的更严了,经测试如下方法可以解决,供参考。

1、AndroidManifest.xml添加权限

   <!-- 安装需要的权限 -->
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

2、AndroidManifest.xml添加provider

  提醒一下有些v4包里面没有FileProvider这个类,那就需要重新下载一个了

    <!--20200616 android 10 以上安装无权限问题 添加provider 添加在application里面 -->
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.figo.test.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true" >
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

3、添加共享文件路径文件xml/file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <paths>
        <!--external-path用来指定Uri共享的
            name属性的值可以随便填
            path属性的值表示共享的具体路径,这里设置为空代表将整个SD卡进行共享,当然你也可以共享存放的图片地址-->
        <external-path name="my_images" path=""/>
    </paths>

</resources>

4、安装apk代码

/**
	 * 安装应用.
	 * @param context Context
	 * @param file File
	 */
	public static void installApp(Context context, File file){
		String fileName = file.getName();
		int index = fileName.lastIndexOf(".");
		String nameExtra = fileName.substring(index + 1, fileName.length());
		if (nameExtra.equals("apk")) {
			
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			if (Build.VERSION.SDK_INT >= 7) { //20200616 android10以上版本安装没有权限报错问题解决 
			    Uri apkUri = FileProvider.getUriForFile(context, "com.figo.test.fileprovider", file); //与manifest中定义的provider中的authorities保持一致
			    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
			} else {
			    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
			}
			context.startActivity(intent);

		}
	}

猜你喜欢

转载自blog.csdn.net/figo0423/article/details/106788577