1,按流程先贴主程序
package com.html; 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; import com.Tools.HttpUtil; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.StrictMode; import android.view.LayoutInflater; import android.view.View; import android.widget.ProgressBar; public class Update_MainActivity extends Activity { /* 下载中 */ private static final int DOWNLOAD = 1; /* 下载结束 */ private static final int DOWNLOAD_FINISH = 2; /* 保存解析的XML信息 */ HashMap<String, String> mHashMap; /* 下载保存路径 */ private String mSavePath; /* 记录进度条数量 */ private int progress; /* 是否取消更新 */ private boolean cancelUpdate = false; /* 更新进度条 */ private ProgressBar mProgress; private Dialog mDownloadDialog; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.update_main); StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads().detectDiskWrites().detectNetwork() // or // .detectAll() // for // all // detectable // problems .penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath() .build()); // 检查软件更新 checkUpdate(); } private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { // 正在下载 case DOWNLOAD: // 设置进度条位置 mProgress.setProgress(progress); break; case DOWNLOAD_FINISH: // 安装文件 installApk(); break; default: break; } }; }; /** * 检测软件更新 */ public void checkUpdate() { if (isUpdate()) { // 显示提示对话框 showNoticeDialog(); } else { Intent intent = new Intent(Update_MainActivity.this, Init.class); startActivity(intent); Update_MainActivity.this.finish(); } } /** * 检查软件是否有更新版本 * * @return */ private boolean isUpdate() { // 获取当前软件版本 int versionCode = getVersionCode(); System.out.println("当前版本号" + versionCode); String sdpath = "http://192.168.0.13:8888/agent/updateApk/version.xml"; InputStream inStream = HttpUtil .GetInputStreamFromURL("http://192.168.0.13:8888/agent/updateApk/version.xml"); System.out.println("sdpath..............." + sdpath); System.out.println("inStream..............." + inStream); // 解析XML文件。 由于XML文件比较小,因此使用DOM方式进行解析 ParseXmlService service = new ParseXmlService(); try { mHashMap = service.parseXml(inStream); } catch (Exception e) { e.printStackTrace(); } if (null != mHashMap) { int serviceCode = Integer.valueOf(mHashMap.get("version")); System.out.println("服务器版本号1" + serviceCode); // 版本判断 if (serviceCode > versionCode) { return true; } } return false; } /** * 获取软件版本号 * * @return */ private int getVersionCode() { int versionCode = 0; try { // 获取软件版本号,对应AndroidManifest.xml下android:versionCode versionCode = Update_MainActivity.this.getPackageManager() .getPackageInfo("com.html", 0).versionCode; } catch (NameNotFoundException e) { e.printStackTrace(); } return versionCode; } /** * 显示软件更新对话框 */ private void showNoticeDialog() { // 构造对话框 System.out.println("显示软件更新对话框"); AlertDialog.Builder builder = new Builder(this); 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(); Intent intent = new Intent(Update_MainActivity.this, Init.class); startActivity(intent); Update_MainActivity.this.finish(); } }); Dialog noticeDialog = builder.create(); noticeDialog.show(); } /** * 显示软件下载对话框 */ private void showDownloadDialog() { // 构造软件下载对话框 System.out.println("构造软件下载对话框"); AlertDialog.Builder builder = new Builder(this); builder.setTitle(R.string.soft_updating); // 给下载对话框增加进度条 final LayoutInflater inflater = LayoutInflater.from(this); 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"; System.out.println("下载存储地址" + mSavePath); URL url = new URL(mHashMap.get("url")); System.out.println("下载地址" + new URL(mHashMap.get("url"))); // 创建连接 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, mHashMap.get("name")); 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(); System.out.println("下载文件"); } }; /** * 安装APK文件 */ private void installApk() { File apkfile = new File(mSavePath, mHashMap.get("name")); if (!apkfile.exists()) { return; } // 通过Intent安装APK文件 Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive"); this.startActivity(intent); } }
2,贴主程序中用到的工具类
检测版本有没有更新,要获取到服务器上version.xml里面的版本号,和本地APK中AndroidMainfest.xml中的versionCode的值比较
package com.Tools; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; public class HttpUtil { // 通过url获得HttpGet对象 public static HttpGet getHttpGet(String url) { // 实例化HttpGet HttpGet request = new HttpGet(url); return request; } // 通过URL获得HttpPost对象 public static HttpPost getHttpPost(String url) { // 实例化HttpPost HttpPost request = new HttpPost(url); return request; } // 通过HttpGet获得HttpResponse对象 public static HttpResponse getHttpResponse(HttpGet request) throws ClientProtocolException, IOException { // 实例化HttpResponse HttpResponse response = new DefaultHttpClient().execute(request); return response; } // 通过HttpPost获得HttpResponse对象 public static HttpResponse getHttpResponse(HttpPost request) throws ClientProtocolException, IOException { // 实例化HttpResponse HttpResponse response = new DefaultHttpClient().execute(request); return response; } // 通过url发送post请求,返回请求结果 public static String queryStringForPost(String url) { // 获得HttpPost实例 HttpPost request = HttpUtil.getHttpPost(url); String result = null; try { // 获得HttpResponse实例 HttpResponse response = HttpUtil.getHttpResponse(request); // 判断是否请求成功 // if(response.getStatusLine().getStatusCode() ==200){ // 获得返回结果 result = EntityUtils.toString(response.getEntity()); return result; // } } catch (ClientProtocolException e) { e.printStackTrace(); result = "网络异常!"; return result; } catch (IOException e) { e.printStackTrace(); result = "网络异常!"; return result; } // return null; } // 通过url发送get请求,返回请求结果 public static String queryStringForGet(String url) { // 获得HttpGet实例 HttpGet request = HttpUtil.getHttpGet(url); String result = null; try { // 获得HttpResponse实例 HttpResponse response = HttpUtil.getHttpResponse(request); // 判断是否请求成功 // if(response.getStatusLine().getStatusCode()==200){ // 获得返回结果 result = EntityUtils.toString(response.getEntity()); return result; // } } catch (ClientProtocolException e) { e.printStackTrace(); result = "网络异常!"; return result; } catch (IOException e) { e.printStackTrace(); result = "网络异常!"; return result; } // return null; } // 通过HttpPost发送Post请求,返回请求结果 public static String queryStringForPost(HttpPost request) { String result = null; try { // 获得HttpResponse实例 HttpResponse response = HttpUtil.getHttpResponse(request); // 判断是否请求成功 // if(response.getStatusLine().getStatusCode()==200){ // 获得请求结果 result = EntityUtils.toString(response.getEntity()); return result; // } } catch (ClientProtocolException e) { e.printStackTrace(); result = "网络异常!"; return result; } catch (IOException e) { e.printStackTrace(); result = "网络异常!"; return result; } // return null; } // 通过HttpGet发送Get请求,返回请求结果 public static String queryStringForGet(HttpGet request) { String result = null; try { // 获得HttpResponse实例 HttpResponse response = HttpUtil.getHttpResponse(request); // 判断是否请求成功 // if(response.getStatusLine().getStatusCode()==200){ // 获得请求结果 result = EntityUtils.toString(response.getEntity()); return result; // } } catch (ClientProtocolException e) { e.printStackTrace(); result = "网络异常!"; return result; } catch (IOException e) { e.printStackTrace(); result = "网络异常!"; return result; } // return null; } public static InputStream GetInputStreamFromURL(String urlstr) { HttpURLConnection connection; URL url; InputStream stream = null; try { url = new URL(urlstr); connection = (HttpURLConnection) url.openConnection(); connection.connect(); stream = connection.getInputStream(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return stream; } }
3通过上面的类获取到服务器上XML的输入流,然后再解析XML取到里面的内容
package com.html; import java.io.InputStream; import java.util.HashMap; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class ParseXmlService { public HashMap<String, String> parseXml(InputStream inStream) throws Exception { HashMap<String, String> hashMap = new HashMap<String, String>(); // 实例化一个文档构建器工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 通过文档构建器工厂获取一个文档构建器 DocumentBuilder builder = factory.newDocumentBuilder(); // 通过文档通过文档构建器构建一个文档实例 Document document = builder.parse(inStream); // 获取XML文件根节点 Element root = document.getDocumentElement(); // 获得所有子节点 NodeList childNodes = root.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { // 遍历子节点 Node childNode = (Node) childNodes.item(j); if (childNode.getNodeType() == Node.ELEMENT_NODE) { Element childElement = (Element) childNode; // 版本号 if ("version".equals(childElement.getNodeName())) { hashMap.put("version", childElement.getFirstChild() .getNodeValue()); System.out.println("服务器版本号2" + childElement.getFirstChild() .getNodeValue()); } // 软件名称 else if (("name".equals(childElement.getNodeName()))) { hashMap.put("name", childElement.getFirstChild() .getNodeValue()); } // 下载地址 else if (("url".equals(childElement.getNodeName()))) { hashMap.put("url", childElement.getFirstChild() .getNodeValue()); } } } return hashMap; } }
4,有了这些就可以比较版本是否有更新,
在网站上存放你的用来更新,的APK和version.xml了。
<update> <version>2</version> <name>NCP_Consume</name> <url>http://192.168.0.13:8888/agent/updateApk/NCP_Consume.apk</url> </update>
5,别忘了加权限在AndroidMainfest.xml里面加上访问网络的权限。根据你android版本不一样加的位置也不一样,貌似2.2的是加载下面。3.0以上要加在上面。总之你的权限下面不能有黄色没有用到提示的波浪线。
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.html" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> </manifest>
倒说第三个权限就是联网的,下面2个挂载和读写SD卡的
特别提示我再平板4.0系统上开发的时候权限加在上面下面都没用,虽然没有黄色提示线。后来找到解决的方法,android3.0以后访问网络的权限的解决办法。在oncreate()中加上这段代码:
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads().detectDiskWrites().detectNetwork() .penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath() .build());
以上就是我做的android软件版本升级代码。后期老总要我做成想WINDOWS那样单独的一个Update升级软件,要每次启动软件默认后台运行,现在卡在后台运行一个APK上面了。等完成后再贴上来把!