public class ServiceApkInstaller {
/**
* 保存到本地
*
* @param context
* @param fileName assets下的文件名
* @param path 存储路径
*/
public void copyApkFromAssets(Activity context, String fileName, String path) {
try {
Logger.e("开始");
InputStream is = context.getAssets().open(fileName);
File file = new File(path);
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
byte[] temp = new byte[1024];
int i = 0;
while ((i = is.read(temp)) > 0) {
fos.write(temp, 0, i);
}
fos.close();
is.close();
installApk(file, context);
Logger.e("完成");
} catch (IOException e) {
e.printStackTrace();
Logger.e("" + e.getMessage());
}
}
/**
* 安装apk (注意在安装apk时的Android7.0配置path的问题)
*
* @param file
* @param c
*/
private void installApk(File file, Activity c) {
if (!file.exists()) {
return;
}
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(c, BuildConfig.APPLICATION_ID + ".fileprovider", file);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
c.startActivityForResult(intent, 88);
}