Android 軟件自動更新 (網絡XML解析、以及本地xml軟件版本兩種解析方式)

XML放入網絡空間—version.xml .url地址應該為正常***/*****.apk
<update>
 <version>5</version>
 <name>yuanbao</name>
 

<url>https://cdn.market.hiapk.com/data/upload//2012/06_27/13/yuanbao.co.

cc_134532.apk
 </url>
</update>
—————-主main
package gognzibai.co.cc;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity
{
 @Override
 public void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  //按鈕更新
  Button updateBtn = (Button) findViewById

(R.id.btnUpdate);
  updateBtn.setOnClickListener(new OnClickListener()
  {
   @Override
   public void onClick(View v)
   {
    UpdateManager manager = new

UpdateManager(MainActivity.this);
   
    manager.checkUpdate();
   }
  });
 
 }
}

—————–ParseXmlService.java
package gongzibai.co.cc;

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;

//解析xml
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 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());
    }
   
    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 gongzibai.co.cc;

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 android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
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.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

 

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 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:
    //安裝APK
    installApk();
    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();
  }
 }

 
 private boolean isUpdate() {
 
  int versionCode = getVersionCode(mContext);
 
  //本地的XML更新
  // InputStream inStream = ParseXmlService.class
  //
  // .getResourceAsStream("version.xml");
  // InputStream inStream = ParseXmlService.class
  // .getClassLoader()
  // .getResourceAsStream(
  // "version1.xml");
 
  //解析網絡xml進行更新軟件
  URL url = null;
  try {
   url = new URL(
    

"https://gongzibai.h001.sjsdidc.cn/version.xml");
  } catch (MalformedURLException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  HttpURLConnection conn = null;
  try {
   conn = (HttpURLConnection) url
     .openConnection();
  } catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  conn.setConnectTimeout(5000);
  InputStream is = null;
  try {
   is = conn.getInputStream();
  } catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }

 
  ParseXmlService service = new ParseXmlService();
  try {
   mHashMap = service
     .parseXml(is);
  } 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(
      

"gongzibai.co.cc",
       0).versionCode;
  } catch (NameNotFoundException e) {
   e.printStackTrace();
  }
  return versionCode;
 }

 
 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 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();
 }

 private void downloadApk() {
 
  new downloadApkThread().start();
 }

 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);
 }
}

 作者:gongzibai
 

發佈留言