android端 版本升级

由于项目中要求实现版本升级,特写此代码,有因为这段代码基本都是通用,所以记录下来,以便下次直接拷贝...

public class ApkVersionUpdate {

    /** apk文件下载状态:正在下载 */
    private static final int DOWNLOADING = 1;

    /** apk文件下载状态:已完成下载 */
    private static final int DOWNLOADED = 2;


    /** 客户端保存到sd卡的路径 */
    private String savePath;

    /** 下载文件对话框 */
    private Dialog downloadDialog;

    /** 下载进度条 */
    private ProgressBar downloadProgressBar;

    /** 下载文件时的进度值 */
    private int progress;

    /** 是否取消更新,默认为否 */
    private boolean cancelUpdate = false;


    private Context mContext;
    private OkHttpHelper httpHelper = OkHttpHelper.getInstance();
    private String downloadurl;
    private String clientVersionCode;
    private String desc;
    private String apkName="sanxin";

    public ApkVersionUpdate(Context context) {
        mContext = context;
        getPackageManage();
    }

    public void checkVersion(final boolean showProgressDialog) {
        final Message msg = Message.obtain();
        Map<String,Object> params = new HashMap<>();
        params.put("ports","children");
        httpHelper.post(HttpUrl.version_url_http, params, new SimpleCallback<Version>(mContext) {
            @Override
            public void onSuccess(Response response, Version item) {
                if(item.getResult()==0){
                    List<Version.VersionItem> list = item.getList();
                    Version.VersionItem versionItem = list.get(0);
                    String serverVersionCode = versionItem.getVersion();

                    downloadurl =versionItem.getDownloadurl();
                    desc = versionItem.getDesc();
                    Log.e("版本",clientVersionCode+"--"+serverVersionCode);

                    // 当最新版本号大于当前版本号时,提示更新
                    if (!serverVersionCode.equals(clientVersionCode)) {
                        if(Integer.valueOf(versionItem.getUpdatevs())==0){
                            showNoticeDialog();
                        }else {
                            showNoticeDialog2();//强制更新
                        }

                    } else {
                        if (showProgressDialog) {
                            Toast.makeText(mContext, "您现在使用的是最新版本哦", Toast.LENGTH_SHORT).show();
                        }
                    }

                }
            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }
        });
    }

    private void showNoticeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("更新提醒");
        builder.setMessage(desc);

        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("下次再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("立刻更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                showDownloadDialog();
            }

        });
        builder.show();
    }
    private void showNoticeDialog2() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("更新提醒");
        builder.setMessage(desc);
        // builder.setCancelable(false);

        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("立刻更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                showDownloadDialog();
            }

        });
        builder.show();
    }
    /**
     * 展示下载对话框
     */
    private void showDownloadDialog() {
        // 构造对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("正在下载");
        // 给下载对话框增加进度条
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.version_update_progress, null);
        downloadProgressBar = (ProgressBar) v.findViewById(R.id.update_progress);
        builder.setView(v);
        // 取消更新
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 隐藏对话框
                dialog.dismiss();
                // 设置取消状态
                cancelUpdate = true;
            }
        });
        downloadDialog = builder.create();
        downloadDialog.show();
        // 下载文件
        downloadApk();
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        new DownloadApkThread().start();
    }

    // 文件下载线程
    private class DownloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                // 判断SD卡是否存在,并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    String sdPath = Environment.getExternalStorageDirectory() + "/";
                    savePath = sdPath + "download";
                    URL url = new URL(downloadurl);
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();
                    File file = new File(savePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(savePath, apkName);
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    // 已下载量
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中,点击取消时停止下载
                    while (!cancelUpdate) {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        downloadHandler.sendEmptyMessage(DOWNLOADING);
                        if (numread <= 0) {
                            // 下载完成
                            downloadHandler.sendEmptyMessage(DOWNLOADED);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    }
                    fos.close();
                    is.close();
                } else {
                    Toast.makeText(mContext, "当前的存储卡不可用,无法完成更新", Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 取消下载对话框显示
            downloadDialog.dismiss();
        }
    };

    /**
     * 安装apk文件
     */
    private void install() {
        File apkFile = new File(savePath, apkName);
        if (apkFile.exists()) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse("file://" + apkFile.toString()),
                    "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        }
    }

    // 文件下载控制器
    private Handler downloadHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOADING:
                    // 正在下载,更新进度条
                    downloadProgressBar.setProgress(progress);
                    break;
                case DOWNLOADED:
                    // 下载完成,安装文件
                    install();
                    break;
                default:
                    break;
            }
        }
    };

    private void getPackageManage() {
        PackageManager packageManager = mContext.getPackageManager();
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(
                    mContext.getPackageName(), 0);
            String version = packInfo.versionName;
            clientVersionCode = String.valueOf(packInfo.versionCode);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

    }
  /*  *//**
     * 多线程的下载器
     *
     * @param downloadurl
     *//*
    private void download(String downloadurl) {
        // 多线程断点下载。
        HttpUtils http = new HttpUtils();
        http.download(downloadurl, "/mnt/sdcard/temp.apk",
                new RequestCallBack<File>() {
                    @Override
                    public void onSuccess(ResponseInfo<File> arg0) {
                        UIUtils.showToast(activity,"下载完成...");
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.VIEW");
                        intent.addCategory("android.intent.category.DEFAULT");

                        intent.setDataAndType(Uri.fromFile(new File(Environment
                                        .getExternalStorageDirectory(), "temp.apk")),
                                "application/vnd.android.package-archive");
                        startActivityForResult(intent, 0);
                    }

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        ToastUtils.show(activity, "下载失败");
                        System.out.println(arg1);
                        arg0.printStackTrace();
                        //loadMainUI();
                    }

                    @Override
                    public void onLoading(long total, long current,
                                          boolean isUploading) {
                        //tv_info.setText(current + "/" + total);
                        super.onLoading(total, current, isUploading);
                    }
                });
    }*/

}

  以上就是版本检测与下载的 工具类, 直接引入项目即可,可能做法比较简单,勿喷... 里面有一个判断==0,表示不需要强制更新,==1表示需要强制更新,根据客户要求做的,就是这个json字段

Integer.valueOf(versionItem.getUpdatevs())==0  

布局如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content">

   <ProgressBar
      android:id="@+id/update_progress"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      style="?android:attr/progressBarStyleHorizontal" />

</LinearLayout>

  

上2个图片




原文地址:https://www.cnblogs.com/android-zcq/p/5542624.html