android_自动检测更新

public class UpdateManager {
    /*检测更新地址*/
    private static final String UPDATEURL =“ 更新地址”;
    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */

    private static final int DOWNLOAD_FINISH = 2;

    /*软件更新对话框*/

    private static final int SHOWNOTICEDIALOG = 3;

   /*最新版本无需更新*/

    private static final int SHOWNOTUPDATA = 4;
    /* 保存解析的XML信息 */
    HashMap<String, String> mHashMap;
    /* 下载保存路径 */
    private String mSavePath;
    /* 记录进度条数量 */
    private int progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;


    private Context mContext;
    /* 更新进度条 */
    private ProgressBar mProgress;
    private Dialog mDownloadDialog;
    private int responseCode;
    private InputStream is;
    private URL url;
    private int serviceCode;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case DOWNLOAD:
                    // 设置进度条位置
                    mProgress.setProgress(progress);
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    installApk();
                    break;
                case SHOWNOTICEDIALOG:
                    showNoticeDialog();
                    break;
                case SHOWNOTUPDATA:
                    Toast.makeText(mContext, R.string.thecurrentisthelatestversion, Toast.LENGTH_LONG).show();
                default:
                    break;
            }
        }  ;
    };


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


    /**
     * 检查软件是否有更新版本
     *
     * @return
     */
    public void isUpdate(final String str) {
        // 解析XML文件。 由于XML文件比较小,因此使用DOM方式进行解析
        final DOMParsexmlUtils service = new DOMParsexmlUtils();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    url = new URL(UPDATEURL);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                HttpURLConnection conn = null;
                try {
                    conn = (HttpURLConnection) url.openConnection();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    conn.setConnectTimeout(10000);
                    conn.setReadTimeout(8000);
                    conn.setDoInput(true);
                    conn.setRequestMethod("GET");
                    conn.setRequestProperty("Content-Type", "text/html");
                    conn.setRequestProperty("Accept-Charset", "utf-8");
                    conn.setRequestProperty("contentType", "utf-8");


                } catch (ProtocolException e) {
                    e.printStackTrace();
                }


                try {
                    is = conn.getInputStream();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (is != null) {
                    try {
                        mHashMap = service.parseXml(is);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (null != mHashMap) {
                    serviceCode = Integer.valueOf(mHashMap.get("version"));
                }
                // 获取当前软件版本
                int versionCode = getVersionCode(mContext);
                if (serviceCode > versionCode) {
                    mHandler.sendEmptyMessage(SHOWNOTICEDIALOG);
                } else {
                    if (str=="manual"){
                        mHandler.sendEmptyMessage(SHOWNOTUPDATA);
                    }
                }
            }
        }.start();
    }


    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    private int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            // 获取软件版本号,对应AndroidManifest.xml下android:versionCode
            versionCode = context.getPackageManager().getPackageInfo("应用包名", 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }


    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog() {
        // 构造对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle(R.string.updataapp);
        builder.setMessage(R.string.areyouupdata);
        // 更新
        builder.setPositiveButton(R.string.updata, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // 显示下载对话框
                showDownloadDialog();
            }
        });
        // 稍后更新
        builder.setNegativeButton(R.string.updata_later, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }


    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog() {
        // 构造软件下载对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle(R.string.updating);
        // 给下载对话框增加进度条
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.progressbar_softupdate, null);
        mProgress = (ProgressBar) v.findViewById(R.id.progressBar_softUpdate);
        builder.setView(v);
        // 取消更新
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // 设置取消状态
                cancelUpdate = true;
            }
        });
        mDownloadDialog = builder.create();
        mDownloadDialog.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() + "/";
                    mSavePath = sdpath + "download";
                    URL url = new URL(mHashMap.get("apkurl"));
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(10000);
                    conn.setReadTimeout(8000);
                    conn.setDoInput(true);
                    conn.setRequestMethod("GET");
                    conn.setRequestProperty("Content-Type", "text/html");
                    conn.setRequestProperty("Accept-Charset", "utf-8");
                    conn.setRequestProperty("contentType", "utf-8");
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();


                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, mHashMap.get("description"));
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 取消下载对话框显示
            mDownloadDialog.dismiss();
        }
    } ;


    /**
     * 安装APK文件
     */
    private void installApk() {
        File apkfile = new File(mSavePath, mHashMap.get("description"));
        if (!apkfile.exists()) {
            return;
        }
        // 通过Intent安装APK文件
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.addFlags(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());
    }


    public void uninstallAPK() {
        Uri packageURI = Uri.parse("package:cn.com.eyesmart.kindergartensafee");
        Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
        mContext.startActivity(uninstallIntent);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值