检查更新是安卓app的常规功能,现在分享一下我做的检查更新的代码,事件触发为点击立即更新按钮。直接上代码:
//创建ProgressDialog对象 m_pDialog = new ProgressDialog(UpdateActivity.this); // 设置进度条风格,风格为圆形,旋转的 m_pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // 设置ProgressDialog 标题 m_pDialog.setTitle("提示"); // 设置ProgressDialog 提示信息 m_pDialog.setMessage("正在下载最新的apk"); // 设置ProgressDialog 的进度条是否不明确 m_pDialog.setIndeterminate(false); // 设置ProgressDialog 是否可以按退回按键取消 m_pDialog.setCancelable(true); // 让ProgressDialog显示 m_pDialog.show(); new DownloadApkAsyncTask().execute("");
/*** * 下载新版本apk并安装 * @author zhangda * */ private class DownloadApkAsyncTask extends AsyncTask{ @Override protected String doInBackground(String... paramArray) { String httpUrl = Constant.URL_PREFIX + "app/mkb_" + newVersionName + ".apk"; final String fileName = "mkb_" + newVersionName + ".apk"; String path = Environment.getExternalStorageDirectory().getPath(); File tmpFile = new File(path + "/mkb"); if (!tmpFile.exists()) { tmpFile.mkdir(); } file = new File(path + "/mkb/" + fileName); try { URL url = new URL(httpUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream is = conn.getInputStream(); //计算文件长度 int lenghtOfFile = conn.getContentLength(); FileOutputStream fos = new FileOutputStream(file); byte[] buf = new byte[1024]; conn.connect(); int len1 = 0; long total = 0; if (conn.getResponseCode() >= 400) { Toast.makeText(UpdateActivity.this, "连接超时", Toast.LENGTH_SHORT).show(); m_pDialog.cancel(); } else { while ((len1 = is.read(buf)) > 0) { total += len1; //total = total + len1 System.out.println((int)((total*100)/lenghtOfFile)); publishProgress((int)((total*100)/lenghtOfFile)); fos.write(buf, 0, len1); } } conn.disconnect(); fos.close(); is.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } @Override protected void onPostExecute(String result) { if(file != null){ m_pDialog.cancel(); Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); startActivity(intent); } } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); System.out.println(values[0]); if(values[0] < 100){ m_pDialog.setProgress(values[0]); } if(values[0] == 100){ m_pDialog.cancel(); UpdateActivity.this.finish(); } } }