关于版本更新

首先在检查版本更新前,我们要知道 版本更新是怎么更新法。版本号和版本名字都在bulid.gradleli里面就是我截图的俩个就是这俩个versionCode 是版本号。 versionName是版本的名字。首先我们要获取versionCode 来和请求到的版本号做比对。当本版本号小于请求的版本号时就是我们要更新啦。这个时候我们首先要弹出一个dialog提醒用户是否更新。如果要更新的话。我们就要请求网络的下载地址。然后安装覆盖原来的APK(注意签名一定要一样,亚要不然直接是安装,而不是覆盖啦)就行版本升级。 

下面把代码附上,首先先把获取的方法写出来,我写的是静态调用的 

/**
 *   获取版本号
 * @param context
 * @return
 */
public static int getVersionCode(Context context){
    // 获取packagemanager的实例
    int version = 0;
    try {
        PackageManager packageManager = context.getPackageManager();
        //getPackageName()是你当前程序的包名
        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        version = packInfo.versionCode;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return version;
}

然后在你想要实现更新的的里面调用方法方法判断是否大于现有的版本号,因为我的是要加载项目就要更新,就写在入口处

// 现有的版本号 比对服务器的版本号
if (PackageUtils.getVersionCode(this)< ServceBean.UERSIONCODE){
// 弹出提示是否更新
    showUpdateDialog();
}else {
    Log.d(TAG, "initUpdata: 赞没有更新版本");
}
 /**
     * 弹出提示更新的dialog
     */
    private void showUpdateDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setCancelable(false);
        dialog.setTitle("版本更新提示");
        dialog.setMessage("檢查到有最新版本,是否更新?");
        dialog.setNegativeButton("暫不更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //跳转到登录界面
                load2Login();
            }
        });
        dialog.setPositiveButton("立刻更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //Toast.makeText(MainActivity.this, "选择确定哦", 0).show();
                loadNewVersionProgress();//下载最新的版本程序
            }
        });
        dialog.show();
    }

这时候要下载版本程序,因为我没有服务器,就直接写的一个网址

/**
 * 下载新版本程序
 */
private void loadNewVersionProgress() {
    final   String uri="http://www.apk.anzhi.com/data3/apk/201703/14/4636d7fce23c9460587d602b9dc20714_88002100.apk";
    final ProgressDialog pd;    //进度条对话框
    pd = new  ProgressDialog(this);
    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    pd.setMessage("正在下载更新");
    pd.setCancelable(false);
    pd.show();
    //启动子线程下载任务
    new Thread(){
        @Override
        public void run() {
            try {
                Log.i(TAG, "loadNewVersionProgress: 22222222");
                File file = getFileFromServer(uri, pd);
                sleep(3000);
                installApk(file);
                Log.i(TAG, "initUpdata: 进度条");
                pd.dismiss(); //结束掉进度条对话框
            } catch (Exception e) {
                //下载apk失败
                Toast.makeText(getApplicationContext(), "下载新版本失败", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        }}.start();
}

同时要开启一个子线程将获取的APK代码

/**
 * 从服务器获取apk文件的代码
 * 传入网址uri,进度条对象即可获得一个File文件
 * (要在子线程中执行哦)
 */
public static File getFileFromServer(String uri, ProgressDialog pd) {
    //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
        try {
            URL url = new URL(uri);
            HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            //获取到文件的大小
            Log.i("gsp", "getFileFromServer: "+conn.getContentLength());
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            long time= System.currentTimeMillis();//当前时间的毫秒数

            File file = new File(Environment.getExternalStorageDirectory(), time+"updata.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);

            byte[] buffer = new byte[1024];
            int len ;
            int total=0;
            while((len =bis.read(buffer))!=-1){
                fos.write(buffer, 0, len);
                total+= len;
                //获取当前下载量
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            Log.i("gsp", "getFileFromServer: ");
            return file;
        }catch (Exception e){
            Log.i("gsp", "getFileFromServer:报错异常 "+e);
        }
    }
    else{
        Log.i("gsp", "getFileFromServer: ");
        return null;
    }
    return null;
}
/**
 * 安装apk
 */
protected void installApk(File file) {
    Intent intent = new Intent();
    //执行动作
    intent.setAction(Intent.ACTION_VIEW);
    //执行的数据类型
    Log.i(TAG, "installApk: 挂掉啦1");
    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
    startActivity(intent);
    Log.i(TAG, "installApk: 挂掉啦2");
}

最后是安装APK,没有贴全部代码 ,这些知识代码的思路和方法。对于初学者来说,方法调用下就可以了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值