这里整理下apk更新升级时需要用到的一些功能块
//这里是我们下载好的apk存放路径
public static String getApkPath(){
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + UpgradeReceiver.APK_NAME;
android.util.Log.i("wwd","updatePath = "+path);
return path;
}
//判断文件是否存在
public boolean fileIsExists(){
String filePath = getApkPath();
try{
File f = new File(filePath);
if(!f.exists()){
return false;
}
}catch (Exception e) {
return false;
}
return true;
}
//判断apk包信息,如果读取不到信息的话说明此APK包为无效包
public boolean getUninsatllApkInfo(Context context) {
boolean result = false;
String filePath = getApkPath();
try {
PackageManager pm = context.getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(filePath,
PackageManager.GET_ACTIVITIES);
String packageName = null;
if (info != null) {
result = true;
android.util.Log.i("wwd","packageName = "+info.packageName);
}
} catch (Exception e) {
result = false;
}
android.util.Log.i("wwd","getUninsatllApkInfo result = "+result);
return result;
}
//获取当前应用版本号,升级前先比较这个版本号是否是最新的
public String getAppVersionName(Context context) {
String versionName = "";
try {
// ---get the package info---
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
versionName = pi.versionName;
if (versionName == null || versionName.length() <= 0) {
return "";
}
} catch (Exception e) {
}
return versionName;
}
//安装应用
public static void installNewApk(final Context context){
String filePath = getApkPath();
Intent installIntent = new Intent(Intent.ACTION_VIEW);
installIntent.setDataAndType(
Uri.fromFile(new File(filePath)),
"application/vnd.android.package-archive");
installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(installIntent);
} catch (Exception e) {
Log.d("wwd", "Failed to launcher installing activity");
}
}
最后把这些功能串起来实现更新apk功能就是
//新APK的版本号
NEW_APP_VERSION = "1.0.2"
public void intallAPP(Context context){
if(fileIsExists() && getUninsatllApkInfo()){
if(!getAppVersionName.equals(NEW_APP_VERSION))
installNewApk(context);
}
}