android更新安装apk

这里整理下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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值