Androidのソフトウェアは自動的に更新してコードを実現します。


どのようにソフトウェアの自動更新を実現しますか?
効果図: 
Android应用自动更新的实现   
Android应用自动更新的实现
Android应用自动更新的实现    
具体的な手順:
1、サーバーに更新用のxmlファイルを配置する:version.xml

<update>
 <version>2</version>
 <name>baiduxinwen.apk</name>
 <url>http://gdown.baidu.com/data/wisegame/e5f5c3b8e59401c8/baiduxinwen.apk</url>
</update>
2、クライアントで更新操作を行う
三つの技術に関して:
   1.xmlファイルの解析
   2.HttpURLConnection接続
   3.ファイルフローI/O
ここで解析xmlファイルのサービスクラスを作成します。PaXml Service.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,      DocumentBuilder。
 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 //  DocumentBuilder,DocumentBuilder          Document  
 DocumentBuilder builder = factory.newDocumentBuilder();
 //        Document  
 Document document = builder.parse(inStream);
 //  XML      
 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;

/**
 * 
 * @author wwj
 * @date 2012/11/17
 *           
 */
public class UpdateManager {
 
 //   ...
 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 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() {
 // TODO Auto-generated method stub
 //     
 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) {
  // TODO Auto-generated method stub
  dialog.dismiss();
  //        
  showDownloadDialog();
  }
 });
 //     
 builder.setNegativeButton(R.string.soft_update_later, new OnClickListener() {
  
  @Override
  public void onClick(DialogInterface dialog, int which) {
  // TODO Auto-generated method stub
  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) {
  // TODO Auto-generated method stub
  dialog.dismiss();
  //       
  cancelUpdate = true;
  }
 });
 mDownloadDialog = builder.create();
 mDownloadDialog.show();
 //    
 downloadApk();
 }
 
 /**
 *   APK  
 */
 private void downloadApk() {
 // TODO Auto-generated method stub
 //          
 new DownloadApkThread().start();
 }


 /**
 *            
 * @return
 */
 public boolean isUpdate() {
 //         
 int versionCode = getVersionCode(mContext);
 // version.xml     ,        
 InputStream inStream = ParseXmlService.class.getClassLoader().getResourceAsStream("version.xml");
 //   XML  。   XML     ,    DOM      
 ParseXmlService service = new ParseXmlService();
 try {
  mHashMap = service.parseXml(inStream);
 } catch (Exception e) {
  // TODO: handle exception
  e.printStackTrace();
 }
 if(null != mHashMap) {
  int serviceCode = Integer.valueOf(mHashMap.get("version"));
  //    
  if(serviceCode > versionCode) {
  return true;
  }
 }
 return false;
 }

 /**
 *        
 * @param context
 * @return
 */
 private int getVersionCode(Context context) {
 // TODO Auto-generated method stub
 int versionCode = 0;

 //        ,  AndroidManifest.xml android:versionCode
 try {
  versionCode = context.getPackageManager().getPackageInfo(
   "com.xiaowu.news", 0).versionCode;
 } catch (NameNotFoundException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 return versionCode;
 }
 
 /**
 *       
 * @author Administrator
 *
 */
 private class DownloadApkThread extends Thread {
 @Override
 public void run() {
  try
  {
  //  SD     ,          
  if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
  {
   //   SDCard   
   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();
 }
 }
 
 /**
 *   APK  
 */
 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);
 }
}

以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。