在客户端实现更新操作
涉及到三个技术:
1.xml文件的解析
2.HttpURLConnection连接
3.文件流I/O
这里创建一个解析xml文件的服务类:ParXmlService.java
- package com.xiaowu.news.update;
-
- 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);
-
- Element root = document.getDocumentElement();
-
- NodeList childNodes = root.getChildNodes();
- for(int i = 0; i < childNodes.getLength(); i++) {
- Node childNode = (Node) childNodes.item(i);
- if(childNode.getNodeType() == Node.ELEMENT_NODE) {
- Element childElement = (Element) childNode;
-
- if("version".equals(childElement.getNodeName())) {
- hashMap.put("version", 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;
- }
- }
实现更新操作的管理类:UpdateManager.java
- package com.xiaowu.news.update;
-
- 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 javax.net.ssl.HttpsURLConnection;
-
- import android.app.AlertDialog;
- import android.app.AlertDialog.Builder;
- import android.app.Dialog;
- import android.content.Context;
- 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.Environment;
- import android.os.Handler;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.widget.ProgressBar;
- import android.widget.Toast;
-
- import com.xiaowu.news.R;
-
- public class UpdateManager {
-
-
- private static final int DOWNLOAD = 1;
-
- private static final int DOWNLOAD_FINISH = 2;
-
- HashMap<String , String> mHashMap;
-
- private String mSavePath;
-
- private int progress;
-
- private boolean cancelUpdate = false;
-
- private Context mContext;
-
- private ProgressBar mProgressBar;
-
- private Dialog mDownloadDialog;
-
-
- private Handler mHandler = new Handler() {
- public void handleMessage(android.os.Message msg) {
- switch(msg.what){
-
- case DOWNLOAD:
-
- System.out.println(progress);
- mProgressBar.setProgress(progress);
- break;
-
- case DOWNLOAD_FINISH:
-
- installApk();
- break;
- }
- };
- };
-
-
- public UpdateManager(Context context) {
- super();
- this.mContext = context;
- }
-
-
-
- public void checkUpdate() {
- if (isUpdate()) {
-
- showNoticeDialog();
- } else {
- Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_SHORT).show();
- }
-
- }
-
- private void showNoticeDialog() {
-
-
- AlertDialog.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() {
-
- AlertDialog.Builder builder = new Builder(mContext);
- builder.setTitle(R.string.soft_updating);
-
- final LayoutInflater inflater = LayoutInflater.from(mContext);
- View view = inflater.inflate(R.layout.softupdate_progress, null);
- mProgressBar = (ProgressBar) view.findViewById(R.id.update_progress);
- builder.setView(view);
- 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();
- }
-
-
- private void downloadApk() {
-
-
- new DownloadApkThread().start();
- }
-
-
-
- public boolean isUpdate() {
-
- int versionCode = getVersionCode(mContext);
-
- InputStream inStream = ParseXmlService.class.getClassLoader().getResourceAsStream("version.xml");
-
- ParseXmlService service = new ParseXmlService();
- try {
- mHashMap = service.parseXml(inStream);
- } catch (Exception e) {
-
- e.printStackTrace();
- }
- if(null != mHashMap) {
- int serviceCode = Integer.valueOf(mHashMap.get("version"));
-
- if(serviceCode > versionCode) {
- return true;
- }
- }
- return false;
- }
-
-
- private int getVersionCode(Context context) {
-
- int versionCode = 0;
-
-
- try {
- versionCode = context.getPackageManager().getPackageInfo(
- "com.xiaowu.news", 0).versionCode;
- } catch (NameNotFoundException e) {
-
- e.printStackTrace();
- }
- return versionCode;
- }
-
-
- private class DownloadApkThread extends Thread {
- @Override
- public void run() {
- try
- {
-
- if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
- {
-
- String sdpath = Environment.getExternalStorageDirectory() + "/";
- mSavePath = sdpath + "download";
- URL url = 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();
- }
- }
-
-
- private void installApk()
- {
- File apkfile = new File(mSavePath, mHashMap.get("name"));
- if (!apkfile.exists())
- {
- return;
- }
- Intent i = new Intent(Intent.ACTION_VIEW);
- i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
- mContext.startActivity(i);
- }
- }
原文地址:http://blog.csdn.net/wwj_748/article/details/8195565
Android - 软件自动更新的实现(转),布布扣,bubuko.com
Android - 软件自动更新的实现(转)
原文:http://www.cnblogs.com/dongweiq/p/3842176.html