版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/rocklee/article/details/85839859
若Compile SDK为Android7或以上, 由于安全问题,Uri只能通过FileProvider.getUriForFile获得.
1/先增加权限
修改AndroidManifest.xml, 增加权限:
<uses-permission android:name="FLAG_GRANT_READ_URI_PERMISSION"/>
<uses-permission android:name="FLAG_GRANT_WRITE_URI_PERMISSION"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
并且在Application节里增加provider节:
<application
android:name=".services.MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.yourpackage.fileProvider"
android:exported="false"
android:grantUriPermissions="true"
>
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
...
com.yourpackage换成你的app的包.
2/修改升级安装代码:
private void installAPK(){
File apkfile = new File(filePathForSave, appVersionInfo.name);
if (!apkfile.exists())
{
return;
}
/*Intent i = new Intent(Intent.ACTION_INSTALL_PACKAGE);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
i.putExtra("EXTRA_RETURN_RESULT", true);
((Activity)context).startActivityForResult(i, REQUEST_CODE);*/
Intent intent = new Intent(Intent.ACTION_VIEW);
//判断是否是AndroidN以及更高的版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", apkfile);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
((Activity)context).startActivity(intent);
}
3/在res资源中增加xml/filepaths.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<paths>
<external-path name="download" path="" />
</paths>
</resources>