안드로이드 APK 자동 업데이트 - andeuloideu APK jadong eobdeiteu

어떻게 소프트웨어 자동 업 데 이 트 를 실현 합 니까?다음은 구체 적 인 실례 입 니 다.
효과 그림: 

안드로이드 APK 자동 업데이트 - andeuloideu APK jadong eobdeiteu
   
안드로이드 APK 자동 업데이트 - andeuloideu APK jadong eobdeiteu

안드로이드 APK 자동 업데이트 - andeuloideu APK jadong eobdeiteu
    
구체 적 인 절차:
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 파일 을 분석 하 는 서비스 클래스 를 만 듭 니 다: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,      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);
 }
}

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.