android 自动检测更新,下载,安装

这里写图片描述这里写图片描述这里写图片描述

import java.io.BufferedReader;
/**
 * 更新功能模块
 * 
 * @author Administrator
 * 
 */
public class UpdateManage {
    private Context mContext;
    // 返回的安装包url
    private String apkUrl = "";
    private Dialog noticeDialog;
    private Dialog downloadDialog;
    // 下载包安装路径
    private static final String savePath = "/sdcard/update/";
    private static String saveFileName = savePath + "UpdateRelease.apk";
    // 进度条与通知ui刷新的handler和msg常量
    private ProgressBar mProgress;
    private TextView update_progress_text;
    private static final int DOWN_UPDATE = 1;
    private static final int DOWN_OVER = 2;
    private static final int REQUEST_S = 3;
    private int progress;
    private Thread downLoadThread;
    private boolean interceptFlag = false;

    private String newVerName = "";// 新版本号
    private String verName = "";// 当前版本号
    // 下载文件大小
    private String apkFileSize;
    // 已下载文件大小
    private String tmpFileSize;

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case DOWN_UPDATE:
                mProgress.setProgress(progress);
                update_progress_text.setText(tmpFileSize + "/" + apkFileSize);
                break;
            case DOWN_OVER:
                downloadDialog.dismiss();
                installApk();
                break;
            case REQUEST_S:
                if (!newVerName.equals(verName)) {
                    showNoticeDialog();
                } else {
                    Toast.makeText(mContext, "当前已是最新版本", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                break;
            }
        }
    };

    public UpdateManage(Context context) {
        this.mContext = context;
    }

    /**
     * 获取当前版本号
     */
    private void getVersion() {
        try {
            PackageManager pm = mContext.getPackageManager();
            PackageInfo pi;
            pi = pm.getPackageInfo(mContext.getPackageName(), 0);
            verName = pi.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取服务器端app版本信息
     * 
     * @return
     */
    private void getServerVersion() {
        new Thread() {
            public void run() {
                try {
                    String respone = Tools.getString(Tools
                            .getInputStream(MyUri.getserverinfo));
                    JSONObject json = new JSONObject(respone);
                    Log.i("updatemanage", json.toString());
                    if (json.getString("flag").equals("true")) {
                        JSONObject result_json = json.getJSONObject("result");
                        newVerName = result_json.getString("version");
                        apkUrl = result_json.getString("downurl");
                    } else {
                        Toast.makeText(mContext, "获取服务端版本信息失败,请稍候重试!", 1)
                                .show();
                    }
                    handler.sendEmptyMessage(REQUEST_S);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            };
        }.start();
    }

    // 获取客户端,服务端版本信息
    private void VersionComparison() {
        getVersion();
        getServerVersion();
    }

    // 外部接口让主Activity调用
    public void checkUpdateInfo() {
        VersionComparison();
    }

    /**
     * 新版本提示dialog
     */
    private void showNoticeDialog() {
        AlertDialog.Builder builder = new Builder(mContext);// 先得到构造器
        builder.setTitle("软件版本更新");// 设置标题
        builder.setMessage("有新版本,是否更新!");// 设置内容
        builder.setIcon(R.drawable.appiconandroid);// 设置图标,图片id即可
        builder.setPositiveButton("下载", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                showDownloadDialog();
            }
        });
        builder.setNegativeButton("以后在说", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        noticeDialog = builder.create();
        noticeDialog.show();
    }

    /**
     * 新版本下载的dialog
     */
    private void showDownloadDialog() {
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle("正在下载中...");
        // 加载进度条布局
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.update_manage_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        update_progress_text = (TextView) v
                .findViewById(R.id.update_progress_text);
        builder.setView(v);
        builder.setNegativeButton("取消", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                interceptFlag = true;
            }
        });
        downloadDialog = builder.create();
        downloadDialog.show();

        downloadApk();// 下载apk

    }

    private Runnable mdownloadApkRunnable = new Runnable() {

        @Override
        public void run() {
            try {

                URL url = new URL(apkUrl);
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(6 * 1000);
                conn.setReadTimeout(5000);
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();// 得到返回的输入流
                //创建apk下载路径文件夹
                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                //创建下载的apk文件,如果没有该文件,写入的时候自动创建
                String apkFile = saveFileName;
                File ApkFile = new File(apkFile);
                FileOutputStream fos = new FileOutputStream(ApkFile);

                int count = 0;
                byte buf[] = new byte[1024];

                // 显示文件大小格式:2个小数点显示
                DecimalFormat df = new DecimalFormat("0.00");
                // 进度条下面显示的总文件大小
                apkFileSize = df.format((float) length / 1024 / 1024) + "MB";

                do {
                    int numread = is.read(buf);
                    count += numread;
                    // 进度条下面显示的当前下载文件大小
                    tmpFileSize = df.format((float) count / 1024 / 1024) + "MB";
                    // 当前进度值
                    progress = (int) (((float) count / length) * 100);
                    // 更新进度
                    handler.sendEmptyMessage(DOWN_UPDATE);
                    if (numread <= 0) {
                        // 下载完成通知安装
                        handler.sendEmptyMessage(DOWN_OVER);
                    }
                    fos.write(buf, 0, numread);
                } while (!interceptFlag);

                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    };

    /**
     * 下载apk
     * 
     */
    private void downloadApk() {
        downLoadThread = new Thread(mdownloadApkRunnable);
        downLoadThread.start();
    }

    /**
     * 安装apk
     */
    private void installApk() {

        File apkFile = new File(saveFileName);
        if (!apkFile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + apkFile.toString()),
                "application/vnd.android.package-archive");
        mContext.startActivity(i);
        android.os.Process.killProcess(android.os.Process.myPid());
    };

}

update_manage_progress.xml布局

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

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

    <TextView
        android:id="@+id/update_progress_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_margin="10dp"
        android:text="" />

</LinearLayout>

在需要检测版本更新的地方,调用此方法

// 检查版本更新
            UpdateManage update = new UpdateManage(MysetActivity.this);
            update.checkUpdateInfo();

在安装方法installApk()中:
如果没有android.os.Process.killProcess(android.os.Process.myPid());最后不会提示完成、打开。
如果没有i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);这一步的话,最后安装好了,点打开,是不会打开新版本应用的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值