解决Android一次打包,安装两个不同apk的问题
接到需求,需要将两个不同的项目APP打包到一个apk安装包里。
不多说,直接干
首先将两个apk,分为主apk和被打包的apk。主apk打包生成,被打包的apk放到Android工程下的assets文件目录夹下。如下图
然后,在本地工程启动页面,执行如下代码,将这个目录下的apk,写到设备本地文件夹里,去安装。
//安装被打包apk(通过调用方法安装,非默认安装)xxxxxxxx.apk,(命名自定义)
public void insetApk() {
if (copyApkFromAssets(this, "xxxxxxxx.apk", Environment.getExternalStorageDirectory().getAbsolutePath() + "/xxxxxx.apk")) {
Builder m = new Builder(mContext)
.setIcon(R.drawable.ic_launcher_round).setMessage("该程序需要安装?")
.setIcon(R.drawable.ic_launcher_round)
.setPositiveButton("yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/xxxxxx.apk"),
"application/vnd.android.package-archive");
mContext.startActivity(intent);
}
});
m.show();
}
}
public boolean copyApkFromAssets(Context context, String fileName, String path) {
boolean copyIsFinish = false;
try {
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();
copyIsFinish = true;
} catch (IOException e) {
e.printStackTrace();
}
return copyIsFinish;
}
存在问题,无法实现静默安装,需要手动触发或在启动页之后才能调用该方法。
另外,需要在高版本上请求安装未知应用来源的权限。
/**
* 判断是否是安卓8.0,安卓8.0需要处理未知应用来源权限问题,否则直接安装
*/
private void checkIsAndroidO() {
if (Build.VERSION.SDK_INT >= 26) {
// PackageManager类中在Android Oreo版本中添加了一个方法:判断是否可以安装未知来源的应用
boolean b = getPackageManager().canRequestPackageInstalls();
if (b) {
AppsUtils.installApk(HomeActivity.this, Environment.getExternalStorageDirectory().getPath(), "testapp.apk");
} else {
//请求安装未知应用来源的权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, INSTALL_PACKAGES_REQUESTCODE);
}
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, REQUESTPERMISSIONCODE);
}
}