android检查版本更新、下载、安装工具类

1.工具类

public class CheckForUpdateUtils {
    private Activity context;
    private Boolean isSelfUpdate;
    private android.os.Handler installHandler;
    private AlertDialog dialog1;
    private ProgressBar progressBar;
    private static final String saveFileName = "studentplatform.apk";
    private CheckForUpdateCallBack checkForUpdateCallBack;
    public CheckForUpdateUtils(Activity context, Boolean isSelfUpdate, CheckForUpdateCallBack checkForUpdateCallBack){
        this.context=context;
        this.isSelfUpdate=isSelfUpdate;
        this.checkForUpdateCallBack=checkForUpdateCallBack;
        installHandler = new android.os.Handler();
    }
    public void getAPPVersion() {
        String strUrl = ApiUrl.UPDATE_APP_URL;
        HttpRequestUtils.getDataRequest(strUrl, ApiID.APIID_UPDATE_APP, context, new HttpRequestUtils.RequestCallBack() {
            @Override
            public void onError() {
                if(isSelfUpdate) {
                    ToastShowUtils.showCommonErrorMsg(context);
                }
            }
            @Override
            public void onResponse(Object response, HeadersResponse headersResponse) {
                if (response != null && response instanceof UpdateAppResponseInfo) {
                    UpdateAppResponseInfo updateAppResponse = (UpdateAppResponseInfo) response;
                    int msg = updateAppResponse.getmMsgCode();
                    if (msg == 1001) {
                        int newVersionCode = updateAppResponse.getmStrUpdateCode();
                        int versionCode = getAppVerCode();
                        if (versionCode >= newVersionCode) {
                            if(isSelfUpdate) {
                                Toast.makeText(context, "已是最新版本,不需要更新!", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            checkForUpdateCallBack.onGetNewVersion();
                            String updateDescription = updateAppResponse.getmStrUpdateDescriptions();
                            String downloadUrl = updateAppResponse.getmStrDownloadUrl();
                            int updateType = updateAppResponse.getmUpdateStatus();
                            CommonLOG.e("updateType","updateType:"+updateType);
                            if (updateType == NetWorkCode.FORCEUPDATEAPP) {
                                CommonLOG.e("dialog","dialog:"+updateType);
                                showSingleBtnDialog(downloadUrl, updateDescription);
                            } else if (updateType == NetWorkCode.UNFORCEUPDATEAPP) {
                                showDoubleBtnDialog(downloadUrl, updateDescription);
                            }
                        }

                    } else {
                        if(isSelfUpdate) {
                            ToastShowUtils.showErrorMessage(context, updateAppResponse.getmStrErrorMessage());
                        }
                    }
                }else {
                    if(isSelfUpdate) {
                        ToastShowUtils.showCommonErrorMsg(context);
                    }
                }
            }
        });
    }
    /**
     * 显示单个按钮的自定义dialog用以强制下载
     * @param strUrl
     * @param describe
     */
    private void showSingleBtnDialog(final String strUrl, String describe) {
        DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener(){
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode==KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        } ;
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View alertDialogView = View.inflate(context, R.layout.dialog_self_singlebtn, null);
        builder.setCancelable(false).setOnKeyListener(keylistener);
        final AlertDialog dialog = builder.create();
        dialog.setView(alertDialogView, 0, 0, 0, 0);
        TextView dialogTitle = (TextView) alertDialogView.findViewById(R.id.dialog_singlebtn_title);
        TextView dialogMsg = (TextView) alertDialogView.findViewById(R.id.dialog_singlebtn_msg);
        Button btnYes = (Button) alertDialogView.findViewById(R.id.dialog_singlebtn_yes);
        dialogTitle.setText("版本更新");
        dialogMsg.setText("检测到新版本\n" + describe);
        btnYes.setText("更新");
        btnYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkForUpdateCallBack.onConfirmClick();
                dialog.dismiss();
                downFile(strUrl);
            }
        });
        dialog.show();
    }

    /**
     * 显示多个按钮的自定义对话框用以非强制下载
     * @param strUrl
     * @param describe
     */
    private void showDoubleBtnDialog(final String strUrl, String describe) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View alertDialogView = View.inflate(context, R.layout.dialog_self_define, null);
        final AlertDialog dialog = builder.create();
        dialog.setView(alertDialogView, 0, 0, 0, 0);
        TextView dialogTitle = (TextView) alertDialogView.findViewById(R.id.dialog_self_title);
        TextView dialogMsg = (TextView) alertDialogView.findViewById(R.id.dialog_self_msg);
        Button btnCancel = (Button) alertDialogView.findViewById(R.id.dialog_self_cancel);
        Button btnYes = (Button) alertDialogView.findViewById(R.id.dialog_self_yes);
        dialogTitle.setText("版本更新");
        dialogMsg.setText("检测到新版本\n" + describe);
        btnYes.setText("更新");
        btnCancel.setText("暂不更新");
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                checkForUpdateCallBack.onCancelClick();
            }
        });
        btnYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                downFile(strUrl);
                checkForUpdateCallBack.onConfirmClick();
            }
        });
        dialog.show();
    }
    private int mCurrentSize = 0;
    private int mUpdateTotalSize = 0;
    private FileOutputStream outputStream;
    private InputStream inputStream;

    private void downFile(final String strUrl) {
        showProgressDialog();
        new Thread() {
            @Override
            public void run() {
                super.run();

                try {
                    HttpURLConnection urlConnection = null;
                    inputStream = null;
                    outputStream = null;
                    URL url = new URL(strUrl);
                    urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestProperty("User-Agent",
                            "PacificHttpClient");
                    if (mCurrentSize > 0) {
                        urlConnection.setRequestProperty("RANGE", "bytes="
                                + mCurrentSize + "-");
                    }
                    mUpdateTotalSize = urlConnection.getContentLength();
                    progressBar.setMax(mUpdateTotalSize);
                    inputStream = urlConnection.getInputStream();

                    if (inputStream != null) {
                        File file = new File(Environment.getExternalStorageDirectory(), saveFileName);
                        outputStream = new FileOutputStream(file);
                        int count = 0;
                        int in = -1;
                        byte buf[] = new byte[1024];
                        while ((in = inputStream.read(buf)) != -1) {
                            outputStream.write(buf, 0, in);
                            count += in;
                            if (mUpdateTotalSize > 0) {
                                progressBar.setProgress(count);
                            }
                        }
                    }

                    outputStream.flush();
                    if (outputStream != null) {
                        outputStream.close();
                    }
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    // 下载完成通知安装
                    updateDown();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }
    private void updateDown() {
        installHandler.post(new Runnable() {
            @Override
            public void run() {
                dialog1.dismiss();
                installApk();
            }
        });
    }
    private void installApk() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment
                        .getExternalStorageDirectory(), saveFileName)),
                "application/vnd.android.package-archive");
        context.startActivity(intent);

    }
    private void showProgressDialog() {
        DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener(){
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode==KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        } ;
        AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
        View progressDialog = View.inflate(context, R.layout.dialog_self_progress, null);
        builder1.setOnKeyListener(keylistener).setCancelable(false);
        dialog1 = builder1.create();
        dialog1.setView(progressDialog, 0, 0, 0, 0);
        TextView progressTitle = (TextView) progressDialog.findViewById(R.id.dialog_progress_title);
        TextView progressMsg = (TextView) progressDialog.findViewById(R.id.dialog_progress_msg);
        progressBar = (ProgressBar) progressDialog.findViewById(R.id.dialog_progress_progressbar);
        progressTitle.setText("版本更新");
        progressMsg.setText("下载中...");
        dialog1.show();
    }
    private int getAppVerCode() {
        int versionCode = -1;
        try {
            String pkName = context.getPackageName();
            versionCode = context.getPackageManager().getPackageInfo(pkName, 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }
}
getAppVersion方法中的联网操作使用的http请求框架不同可能有所不同。单应该所有的http请求回调方法都有一个成功的回调和一个失败的回调。本人使用的自己封装的okhttp,方法类似

2.用到的布局

单按钮对话框:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#aa000000">
    <LinearLayout
        android:id="@+id/dialog_singlebtn_ll_dialog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center"
        android:background="@drawable/dialog_circular_bg"
        android:paddingLeft="24dp"
        android:paddingRight="24dp">
        <TextView
            android:id="@+id/dialog_singlebtn_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Title"
            android:layout_marginTop="10dp"
            android:textSize="@dimen/text_size_middle"
            android:paddingBottom="14dp"
            android:paddingTop="14dp"
            android:textColor="@color/black"/>
        <TextView
            android:id="@+id/dialog_singlebtn_msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="message"
            android:textSize="@dimen/text_size_context"
            android:textColor="@color/black"/>

            <Button
                android:id="@+id/dialog_singlebtn_yes"
                android:layout_width="match_parent"
                android:layout_height="58dp"
                android:text="确定"
                android:paddingTop="14dp"
                android:background="@null"
                android:paddingBottom="20dp"
                android:layout_gravity="center_horizontal"
                android:textSize="@dimen/text_size_small"
                android:textColor="@color/actionbar_bg"
                />
    </LinearLayout>

</FrameLayout>


双按钮对话框:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#aa000000">
    <LinearLayout
        android:id="@+id/dialog_self_ll_dialog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center"
        android:background="@drawable/dialog_circular_bg"
        android:paddingLeft="24dp"
        android:paddingRight="24dp">
        <TextView
            android:id="@+id/dialog_self_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Title"
            android:layout_marginTop="24dp"
            android:textSize="@dimen/text_size_middle"
            android:layout_marginBottom="14dp"
            android:textColor="@color/black"/>
        <TextView
            android:id="@+id/dialog_self_msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="message"
            android:textSize="16sp"
            android:textColor="@color/black"/>
    <RelativeLayout
        android:id="@+id/dialog_self_rl_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical">

        <Button
            android:id="@+id/dialog_self_yes"
            android:layout_width="wrap_content"
            android:layout_height="58dp"
            android:text="@string/dialog_self_yes"
            android:background="@null"
            android:layout_alignParentRight="true"
            android:textSize="13sp"
            android:paddingTop="14dp"
            android:paddingBottom="20dp"
            android:textColor="@color/color_0dc5c5"
            />
        <Button
            android:id="@+id/dialog_self_cancel"
            android:layout_width="wrap_content"
            android:layout_height="58dp"
            android:layout_toLeftOf="@id/dialog_self_yes"
            android:text="@string/dialog_self_cancel"
            android:paddingTop="14dp"
            android:paddingBottom="20dp"
            android:textColor="@color/color_0dc5c5"
            android:background="@null"
            android:layout_marginRight="8dp"
            android:textSize="13sp"/>
    </RelativeLayout>
    </LinearLayout>

</FrameLayout>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值