由于安卓7.0加强了用户权限问题,所以我们需要稍作修改,让我们的程序正常升级安装apk
1.首先在res下建立一个xml文件夹
我们随便起个名字,就叫file_path好了
这里注意我们要修改里面的包名和文件夹名改成自己程序的
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path path="Android/data/包名/" name="files_root"/>
<external-path path="." name="external_storage_root"/>
<external-path name="external_storage_download" path="文件夹名" />
</paths>
AndroidManifast中加权限 <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />//7.0必加这句
application里
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileProvider"//这里.前面也可换成自己的包名
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>//这里注意是xml里的文件名
</provider>
下面是我们安装代码的部分
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/文件夹名/需要安装的apk名.apk";
File file = new File(path);
if (!file.exists()) {
return;
}
install(this,path);
public static boolean install(Context con, String filePath) {
try {
File file = new File(filePath);
if(file.exists()){
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//增加读写权限
}
intent.setDataAndType(getPathUri(con, filePath), "application/vnd.android.package-archive");
con.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(con, "安装失败,请重新下载", Toast.LENGTH_LONG).show();
return false;
}
catch (Error error) {
error.printStackTrace();
Toast.makeText(con, "安装失败,请重新下载", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
把install放在下载之后或者点击事件之后即可