问题
通过网络下载apk,完成后安装解析失败
原因
下载后的文件和原文件大小不一样,可能流写入问题
原代码
while ((len = is.read(bytes)) != -1) {
// 主要就是这里
// fos.write(bytes); // 这样有可能导致流写入问题
fos.write(bytes,0,len); //在这里使用另一个重载,防止流写入的问题.
}
安装,适配7.0问题
private void install(File file) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//判读版本是否在7.0以上
Uri apkUri = FileProvider.getUriForFile(this, "包名.fileprovider", file);//在AndroidManifest中的android:authorities值
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
install.setDataAndType(apkUri, "application/vnd.android.package-archive");
startActivity(install);
}else{
//以前的启动方法
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(install);
}
}
在清单文件添加
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="包名.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
在res中创建文件夹xml,创建文件,file_paths.xml
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<paths>
<external-path path="" name="download"/>
</paths>
</resources>