一套完整的APP版本更新代码

本文转载至IT985博客:点击打开链接


在很多APP中版本更新是最基本的一个功能了,那么从检查版本更新到下载自动安装这一系列过程改如何实现呢,当然有很多方式,这里我总结了一种其中很基本的方式。

这是效果图:
pic

 

 

 

 

 

检查更新这个就不多说啦,这里我用的是通过OkHttpUtils网络请求框架来检测新版本。当然OkHttpUtils也有自己的下载功能,但是好像有很多限制,其中文件过大就会下载失败内存溢出等问题。

publicvoid checkUpdate(Activity activity, finalboolean isShowTip) {
    OkHttpUtils.get().url(Url.UPDATE_VERSION).build().execute(newStringCallback() {
        @Override
        publicvoid onError(Call call, Exception e, intid) {
 
        }
 
        @Override
        publicvoid onResponse(String response, intid) {
            finalJsonData jsonData = JsonData.create(response);
            intversionCode = jsonData.optInt("version");
            intcurrentVersionCode = SystemUtils.getAppVersionCode(context);
            if(versionCode > currentVersionCode) {
                AlertDialog.Builder builder = newAlertDialog.Builder(context);
                builder.setTitle("更新");
                builder.setMessage("检测到有更新,是否立刻更新?");
                builder.setNegativeButton("稍后更新", newDialogInterface.OnClickListener() {
 
                    @Override
                    publicvoid onClick(DialogInterface dialog, intwhich) {
                    }
                });
                builder.setPositiveButton("立刻更新", newDialogInterface.OnClickListener() {
 
                    @Override
                    publicvoid onClick(DialogInterface dialog, intwhich) {
                        if(!StringUtils.isWifi(context)) {
                            AlertDialog.Builder builder = newAlertDialog.Builder(context);
                            builder.setTitle("提示");
                            builder.setMessage("您当前正在使用移动网络,继续下载将消耗流量");
                            builder.setNegativeButton("取消", newDialogInterface.OnClickListener() {
 
                                @Override
                                publicvoid onClick(DialogInterface dialog, intwhich) {
 
                                }
                            });
                            builder.setPositiveButton("确定", newDialogInterface.OnClickListener() {
 
                                @Override
                                publicvoid onClick(DialogInterface dialog, intwhich) {
                                    downLoadApk(jsonData.optString("download"));
                                }
                            });
                            builder.create().show();
                        } else{
                            downLoadApk(jsonData.optString("download"));
                        }
                    }
                });
                builder.create().show();
            } else{
                if(isShowTip) {
                    ToastUtils.show(context, "当前已是最新版本");
                }
            }
        }
 
    });
}
 
/*
   * 从服务器中下载APK
*/
  protectedvoid downLoadApk(finalString url) {
      finalProgressDialog pd;    //进度条对话框
      pd = newProgressDialog(this);
      pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
      pd.setMessage("正在下载更新");
      pd.show();
      newThread() {
          @Override
          publicvoid run() {
              try{
                  File file = DownLoadManager.getFileFromServer(url, pd);
                  sleep(3000);
                  installApk(file);
                  pd.dismiss(); //结束掉进度条对话框
              } catch(Exception e) {
                  Toast.makeText(context, "下载失败!",
                          Toast.LENGTH_SHORT).show();
                  e.printStackTrace();
              }
          }
      }.start();
  }
 
  //安装apk
  protectedvoid installApk(File file) {
      Intent intent = newIntent();
      //执行动作
      intent.setAction(Intent.ACTION_VIEW);
      //执行的数据类型
      intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
      startActivity(intent);
  }

这里是下载数据的代码DownLoadManager.java

importjava.io.BufferedInputStream;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.URL;
 
importandroid.app.ProgressDialog;
importandroid.os.Environment;
 
publicclass DownLoadManager {
 
    publicstatic File getFileFromServer(String path, ProgressDialog pd) throwsException {
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = newURL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            //获取到文件的大小
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            File file = newFile(Environment.getExternalStorageDirectory(), "某某某.apk");
            FileOutputStream fos = newFileOutputStream(file);
            BufferedInputStream bis = newBufferedInputStream(is);
            byte[] buffer = newbyte[1024];
            intlen;
            inttotal = 0;
            while((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                //获取当前下载量
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            returnfile;
        } else{
            returnnull;
        }
    }
}


  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值