最近在项目中,需要将应用B和应用A打包在一起,然后应用A安装完成启动时,对应用B自动进行安装。如何实现呢?
首先,我们先检测应用B是否已安装,若已安装,版本号是否比待安装的版本号低,否则就没有安装的必要了。直接上代码:
private boolean checkAppNeedUpdate(String packageName){
if (packageName == null){
return false;
}
PackageManager pm = this.getPackageManager();
List<PackageInfo> infoList = pm.getInstalledPackages(0);
if (infoList != null && !infoList.isEmpty()){
for (PackageInfo info : infoList){
logger.error("已安装应用包名:" + info.packageName);
if (packageName.equals(info.packageName)){
//检查安装版本是否最新
String apkPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "appB.apk";
PackageInfo pi = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
if (pi != null){
int newVersionCode = pi.versionCode;
if (newVersionCode <= info.versionCode){
return true;
}
}
return false;
}
}
}
return false;
}
判断完毕,若需要安装,由于应用B的安装包文件位于应用A工程中的assets目录下,因此,我们需要将apk文件以输入流的方式读写到sd卡中,然后从sd卡中进行安装。代码如下:
private boolean copyApkFromAssets(Context context, String fileName, String targetPath){
boolean isCopySuccess = false;
try {
//从assets下创建输入流
InputStream is = context.getAssets().open(fileName);
//新建保存路径下的file,构建输出流
File file = new File(targetPath);
if (!file.exists()){
file.createNewFile();
}
FileOutputStream os = new FileOutputStream(file);
//读写
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) > 0){
os.write(buffer, 0, len);
os.flush();
}
os.close();
is.close();
isCopySuccess = true;
}catch (IOException e){
e.printStackTrace();
}
return isCopySuccess;
}
以上是基本的文件读写操作,不再赘述,主要注意一下从assets下读取输入流的方法。
最后,我们启动系统的安装intent,对应用B进行安装:
Intent installIntent = new Intent(Intent.ACTION_VIEW);
installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
installIntent.setDataAndType(Uri.parse("file://" + path), "application/vnd.android.package-archive");
startActivity(installIntent);