<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">Compile Sdk Version:API 21: Android 4.X (L Preview)</span>
Build Tools Version:21.1.2
Min Sdk Version:API 9: Android 2.3 (Gingerbread)
UpdateManger.java类
package com.kkjspt.business; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; /** *@author coolszy *@date 2015-5-8 *@酷酷kkjspt.com */ public class UpdateManager { /* 下载中 */ private static final int DOWNLOAD = 1; /* 下载结束 */ private static final int DOWNLOAD_FINISH = 2; private static final int DOWNLOADJSON = 3; /* 保存解析的XML信息 */ HashMap<String, String> mHashMap; /* 下载保存路径 */ private String mSavePath; /* 记录进度条数量 */ private int progress; /* 是否取消更新 */ private boolean cancelUpdate = false; //下载版本xml文件成功 private static final int DOWNLOAD_XML= 3; public static int ServerVersion = 0; public static String ServerAppdownurl = "http://kkjspt.com/kukusoft/appgjh/gjh.app"; public static String ServerAppname = "gjh.app"; private Context mContext; /* 更新进度条 */ private ProgressBar mProgress; private Dialog mDownloadDialog; 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 DOWNLOADJSON: checkUpdate(); break; default: break; } }; }; public UpdateManager(Context context) { this.mContext = context; } /** * 检测软件更新 */ public void checkUpdate() { if (isUpdate()) { // 显示提示对话框 showNoticeDialog(); } else { Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show(); } } /** * 访问版本控制json */ protected void downloadJson() { // 启动新线程下载软件 new fangwenjson().start(); } /** * 检查软件是否有更新版本 * * @return */ private boolean isUpdate() { // 获取当前软件版本 int versionCode = getVersionCode(mContext); if (ServerVersion>versionCode) { return true; } return false; } /** * 下载文件线程 * * @author kkjspt.com *@date 2015-05-13 *@blog http://kkjspt.com */ private class fangwenjson extends Thread { @Override public void run() { try { //服务器 :服务器项目 :servlet名称 String path="http://192.168.137.1/Admin/AppUpdate/"; HttpGet httpGET=new HttpGet(path); HttpResponse response=new DefaultHttpClient().execute(httpGET); if(response.getStatusLine().getStatusCode()==200){ HttpEntity entity=response.getEntity(); String jsonstr= EntityUtils.toString(entity, HTTP.UTF_8); JSONObject jsonObject = new JSONObject(jsonstr); String success = jsonObject.get("success").toString(); JSONObject result = jsonObject.getJSONObject("update"); String version = result.getString("version").toString().trim(); String appdownurl = result.getString("appdownurl"); String name = result.getString("name"); if(version!="") { mHandler.sendEmptyMessage(DOWNLOADJSON); ServerVersion= Integer.parseInt(version); ServerAppdownurl=appdownurl; ServerAppname=name; } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }; /** * 获取软件版本号 * * @param context * @return */ private int getVersionCode(Context context) { int versionCode = 0; try { // 获取软件版本号,对应AndroidManifest.xml下android:versionCode versionCode = context.getPackageManager().getPackageInfo(context.getPackageName(),0).versionCode; } catch (NameNotFoundException e) { e.printStackTrace(); } return versionCode; } /** * 显示软件更新对话框 */ private void showNoticeDialog() { // 构造对话框 Builder builder = new Builder(mContext); 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() { // 构造软件下载对话框 Builder builder = new Builder(mContext); builder.setTitle(R.string.soft_updating); // 给下载对话框增加进度条 final LayoutInflater inflater = LayoutInflater.from(mContext); View v = inflater.inflate(R.layout.loading, 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(); } /** * 下载文件线程 * * @author kkjspt.com *@date 2015-05-13 *@blog http://kkjspt.com */ private class downloadApkThread extends Thread { @Override public void run() { try { // 判断SD卡是否存在,并且是否具有读写权限 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // 获得存储卡的路径 String sdpath = Environment.getExternalStorageDirectory() + "/"; mSavePath = sdpath + "gjh/app/"; // URL url = new URL(mHashMap.get("url")); URL url = new URL(ServerAppdownurl); // 创建连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); // 获取文件大小 int length = conn.getContentLength(); // 创建输入流 InputStream is = conn.getInputStream(); File file = new File(mSavePath); // 判断文件目录是否存在 if (!file.exists()) { file.mkdirs();//创建多层次目录 // file.mkdir();//创建单层目录 } File apkFile = new File(mSavePath,ServerAppname); 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,ServerAppname); 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"); mContext.startActivity(i); } }
values/strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <!--软件更新检测--> <string name="soft_update_no">您当前的软件是最新版本</string> <string name="soft_update_title">提示</string> <string name="soft_update_info">您当前的软件版本已过期,请下载最新版本!</string> <string name="soft_update_updatebtn">开始更新</string> <string name="soft_update_later">稍后更新</string> <string name="soft_updating">正在下载最新的程序安装包</string> <string name="softupdate_progress">更新进度条</string> <string name="soft_update_cancel">取消更新</string> </resources>
values/ids.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <item type="id" name="update_progress" /> </resources>
layout/loading.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ProgressBar style="@android:style/Widget.ProgressBar.Horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@id/update_progress" /> </LinearLayout>
在需要的地方引用
UpdateManager um=new UpdateManager(satrt.this); um.downloadJson();//软件版本更新检测