最近做了一个项目,加了一个自动更新的模块了,自己找了些网络上的资料,根据自己的理解,整理下:
要自动更新,首先得在用户启动应用的时候,去获取服务器当前应用的版本,然后与当前应用的app的版本做比较。当服务器版本大于当前版本时,就提示用户进行更新操作。
这里我这边主要用到一个管理类
public class UpdateManager { private String TAG = "UpdateManager"; /* 下载中 */ private static final int DOWNLOAD = 1; /* 下载结束 */ private static final int DOWNLOAD_FINISH = 2; /* 下载保存路径 */ private String mSavePath; /* 记录进度条数量 */ private int progress; /* 是否取消更新 */ private boolean cancelUpdate = false; private Activity mActivity; /* 更新进度条 */ private ProgressBar mProgress; private Dialog mDownloadDialog; private String FileName; private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { // 正在下载 case DOWNLOAD: // 设置进度条位置 mProgress.setProgress(progress); break; case DOWNLOAD_FINISH: // 安装文件 installApk(); //openApp(); break; default: break; } }; }; /** * 打开app * * @param cmdEntity */ private boolean openApp() { Intent intent = new Intent(); intent = mActivity.getPackageManager().getLaunchIntentForPackage("com.ying.tunel"); if (intent != null) { mActivity.startActivity(intent); return true; } return false; } public UpdateManager(Activity act) { this.mActivity = act; } /** * 检测软件更新 */ public void checkUpdate() { LogTool.i(TAG, "是否需要更新"); try { if (isUpdate()) { // 显示提示对话框 mActivity.runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub showNoticeDialog(); } }); } else { LogTool.i(TAG, "it is lastest Version"); } } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 检查软件是否有更新版本 * * @return */ private boolean isUpdate() throws XmlPullParserException { try { // 获取当前软件版本 final int versionCode = getVersionCode(mActivity); LogTool.i(TAG, "获取xmlUrl==" + UrlConfig.VERSIONURL + "v.html"); Msg msg = httpUtils.doGet(UrlConfig.VERSIONURL + "v.html"); LogTool.i(TAG, msg.toString()); int version = msg.getVersion(); FileName = msg.getFileName(); if (versionCode < version) { return true; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } /** * 获取软件版本号 * * @param context * @return */ private int getVersionCode(Context context) { int versionCode = 0; try { // 获取软件版本号,对应AndroidManifest.xml下android:versionCode versionCode = context.getPackageManager().getPackageInfo("com.ying.tunel", 0).versionCode; } catch (NameNotFoundException e) { e.printStackTrace(); } return versionCode; } /** * 显示软件更新对话框 */ private void showNoticeDialog() { // 构造对话框 AlertDialog.Builder builder = new Builder(mActivity); builder.setTitle(R.string.soft_update_title); builder.setMessage(R.string.soft_update_info); // 更新 builder.setPositiveButton(R.string.soft_update_updatebtn, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); // 显示下载对话框 showDownloadDialog(); } }); // 稍后更新 builder.setNegativeButton(R.string.soft_update_later, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog noticeDialog = builder.create(); noticeDialog.show(); } /** * 显示软件下载对话框 */ private void showDownloadDialog() { // 构造软件下载对话框 AlertDialog.Builder builder = new Builder(mActivity); builder.setTitle(R.string.soft_updating); // 给下载对话框增加进度条 final LayoutInflater inflater = LayoutInflater.from(mActivity); View v = inflater.inflate(R.layout.softupdate_progress, null); mProgress = (ProgressBar) v.findViewById(R.id.update_progress); builder.setView(v); // 取消更新 builder.setNegativeButton(R.string.soft_update_cancel, new 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"; LogTool.i(TAG, "getapkurl==" + UrlConfig.VERSIONURL + FileName); URL url = new URL(UrlConfig.VERSIONURL + FileName); // 创建连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); // 获取文件大小 int length = conn.getContentLength(); // 创建输入流 InputStream is = conn.getInputStream(); File file = new File(mSavePath); // 判断文件目录是否存在 if (!file.exists()) { file.mkdir(); } File apkFile = new File(mSavePath, FileName); 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, FileName); if (!apkfile.exists()) { return; } // 通过Intent安装APK文件 Intent i = new Intent(Intent.ACTION_VIEW); i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive"); mActivity.startActivity(i); } }
在应用启动的时候调用如下方法,开启线程进行自动更新的操作
/** * 自动更新的方法 */ private void update() { final UpdateManager um = new UpdateManager(this); new Thread(new Runnable() { public void run() { um.checkUpdate(); } }).start(); }
由于自己很少写博客,大部分的东西都是通过直接上代码来了展示,记录下来希望以后自己再做这个模块不用再去花时间去招资料了