App 更新

//检查版本号是否更新APP
    public void checkAppNewVersion() {
        if (null == mainActivity) return;
        Api.getUpdateApp(mainActivity, new CallbackHttp() {
            @Override
            public void onResult(boolean isSuccess, int code, String msg, String result, int is_set_pay_pw) {
                if (isSuccess) {
                    BeanNewVersion beanNewVersion = (BeanNewVersion) DubJson.fromJson(result, BeanNewVersion.class);
                    if (null != beanNewVersion && Integer.valueOf(beanNewVersion.getServerFlag()) > ToolUtils.getCurrentVersionCode(mainActivity))
                        (new DialogTool(mainActivity)).checkCreateDownloadUpgradeDialog(beanNewVersion);
                } else {
                    DubToastUtils.showToastNew(msg);
                }
            }
        });
    }
public class BeanNewVersion {
    private String appname;
    private String serverVersion;
    private String serverFlag;
    private int lastForce;
    private String updateurl;
    private String upgradeinfo;

    public String getAppname() {
        return appname;
    }

    public void setAppname(String appname) {
        this.appname = appname;
    }

    public String getServerVersion() {
        return serverVersion;
    }

    public void setServerVersion(String serverVersion) {
        this.serverVersion = serverVersion;
    }

    public String getServerFlag() {
        return serverFlag;
    }

    public void setServerFlag(String serverFlag) {
        this.serverFlag = serverFlag;
    }

    public boolean isLastForce() {
        return lastForce == 2;
    }

    public String getUpdateurl() {
        return updateurl;
    }

    public void setUpdateurl(String updateurl) {
        this.updateurl = updateurl;
    }

    public String getUpgradeinfo() {
        return upgradeinfo;
    }

    public void setUpgradeinfo(String upgradeinfo) {
        this.upgradeinfo = upgradeinfo;
    }
}
public class DialogTool {
    private BaseActivity context;

    public nDialogTool(BaseActivity context) {
        this.context = context;
    }

    /版本更新提示对话框//
    public void checkCreateDownloadUpgradeDialog(final BeanNewVersion newVersionInfo) {
        if (null != newVersionInfo) {
            ToolUtils.showAlertInfoDialog(context, "发现新的版本" + (newVersionInfo.isLastForce() ?
                    "(有重大修改,请立即升级)" : ""), "当前版本:V" + ToolUtils.getCurrentVersionName(context) +
                            "\n新版本号:V" + newVersionInfo.getServerVersion() +
                            "\n更新信息:\n" + newVersionInfo.getUpgradeinfo(),
                    newVersionInfo.isLastForce() ? "狠心退出" : "暂不更新", "立即升级", new nAlertDialog.OnClickListener() {
                @Override
                public boolean onClick(DialogInterface dialogInterface, int flag) {
                    if (newVersionInfo.isLastForce()) {
                        context.minimizationProgram();
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }//end of if
                    return false;
                }
            }, new AlertDialog.OnClickListener() {
                @Override
                public boolean onClick(DialogInterface dialogInterface, int flag) {
                    startDownloadUpgradeApplication(newVersionInfo.getServerVersion(), newVersionInfo.getUpdateurl());
                    return false;
                }
            });
        }//end of if
    }

    public void startDownloadUpgradeApplication(String newCodeName, String appUrl) {
        final String downloadApkPath = ToolUtils.getSD_CardRootPath() + "/" + Url.Project_Dir + "/" + context.getString(R.string.app_name) + newCodeName + ".apk";
        View downloadV = LayoutInflater.from(context).inflate(R.layout.dialog_update_download_layout, null);
        final TextView progressT = (TextView) downloadV.findViewById(R.id.progressT);
        final ProgressBar downloadPb = (ProgressBar) downloadV.findViewById(R.id.progressBar);
        final TextView otherInfoT = (TextView) downloadV.findViewById(R.id.otherInfoT);
        AlertDialog.Builder builder = new nAlertDialog.Builder(context);
        builder.setTitle("升级下载中");
        builder.setContentView(downloadV);
        builder.setContentViewParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        final AlertDialog downloadDialog = builder.create();
        if (null != downloadDialog) downloadDialog.show();
        DownloadAsyncTask DownloadAsyncTask = new DownloadAsyncTask(appUrl, downloadApkPath, new DownloadAsyncTask.DownloadCallback() {
            @Override
            public void onDownloadPrepare() {
                ToolUtils.ViewAndDeleteDirOrFile(downloadApkPath);
                downloadPb.setMax(100);
                downloadPb.setProgress(0);
                progressT.setText("0%");
            }

            @Override
            public void onChangeProgress(int progress, int current, int total) {
                int curProgress = (int) (((float) current / (float) total) * 100);
                progressT.setText(curProgress + "%");
                downloadPb.setProgress(curProgress);
                DecimalFormat df = new DecimalFormat("#.##");
                otherInfoT.setText(df.format((double) current / 1024 / 1024) + "MB/" + df.format((double) total / 1024 / 1024) + "MB");
            }

            @Override
            public void onCompleted(String successMsg) {
                ToolUtils.showLongHintInfo(context, "新版本已经成功下载,请立即安装!");
                if (null != downloadDialog) downloadDialog.dismiss();
                ToolUtils.installApk(context, downloadApkPath);
            }

            @Override
            public void onException(String errorMsg) {
                ToolUtils.showLongHintInfo(context, "新版本更新失败!\n异常信息:" + errorMsg);
                if (null != downloadDialog) downloadDialog.dismiss();
            }

            @Override
            public boolean onCancel() {
                return false;
            }
        });
        DownloadAsyncTask.execute();
    }
}
public class DownloadAsyncTask extends AsyncTask<String, Integer, String> {
    private final String NetFail = "NetFail",Success = "Success",Fail = "Fail";
    private DownloadCallback downCallBack;
    private HttpURLConnection urlConn;
    private String downloadUrl;
    private String saveFilePath;
    private boolean isCancel = false;

    public DownloadAsyncTask(String downloadUrl, String saveFilePath, DownloadCallback downloadCallback){
        this.downCallBack = downloadCallback;
        this.downloadUrl = downloadUrl;
        this.saveFilePath = saveFilePath;
    }

    @Override
    protected void onPreExecute() {
        downCallBack.onDownloadPrepare();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... args) {
        String result = "";
        if(!NetworkUtil.checkURL(downloadUrl)){
            result = NetFail;
        }else{
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                URL url = new URL(downloadUrl);
                urlConn = (HttpURLConnection)url.openConnection();
                is = urlConn.getInputStream();
                int length = urlConn.getContentLength();

                File file = new File(saveFilePath);
                ToolUtils.ViewOrCreateDir(file.getParentFile().getAbsolutePath());
                ToolUtils.ViewAndDeleteDirOrFile(saveFilePath);
                fos = new FileOutputStream(saveFilePath);

                int count = 0,numread = 0;
                byte buf[] = new byte[1024];
                while(!isCancel && (numread = is.read(buf))!=-1){
                    count+=numread;
                    int progressCount =(int)(((float)count / length) * 100);
                    publishProgress(progressCount,count,length);
                    fos.write(buf, 0, numread);
                }
                fos.flush();
                if(count == length){
                    result = Success;
                }else{
                    result = Fail;
                }
            } catch (Exception e) {
                e.printStackTrace();
                result = Fail;
            }finally{
                try {
                    if(null != fos)
                        fos.close();
                    if(null != is)
                        is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    result = Fail;
                }
            }
        }
        return result;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        downCallBack.onChangeProgress(values[0],values[1],values[2]);
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        if(Success.equals(result)){
            downCallBack.onCompleted("已经成功下载!");
        }else if(NetFail.equals(result)){
            downCallBack.onException("连接服务器失败,请稍后重试!");
        }else{
            downCallBack.onException("下载失败,请稍后重试!");
        }
        super.onPostExecute(result);
    }

    @Override
    protected void onCancelled() {
        if(null != urlConn)urlConn.disconnect();
        super.onCancelled();
        isCancel = true;
        downCallBack.onCancel();
    }

    public interface DownloadCallback {
        void onDownloadPrepare();
        void onChangeProgress(int progress, int current, int total);
        void onCompleted(String successMsg);
        void onException(String errorMsg);
        boolean onCancel();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值