android之程式自動更新的實現

來源:互聯網
上載者:User

應用都有版本的更新,那麼怎樣實現更新呢?今天就為大家介紹應用自動更新的全過程。

程式自動更新的流程大致如下:

程式啟動 -->適時後台檢查更新--->連結遠程伺服器-->擷取新版本資訊

-->比對目前的版本-->if(有更新)-->顯示更新提示對話方塊並顯示更新的內容-->交與使用者選擇.


下面是我做的demo,大家可以參考一下:

布局比較簡單就不上代碼了。

主程式碼:

package com.cloay.update;import java.io.IOException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import android.app.Activity;import android.app.AlertDialog;import android.content.DialogInterface;import android.content.pm.PackageManager.NameNotFoundException;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;/** * 程式自動更新 * UpdateTestActivity.java * @author Cloay * 2011-11-23 */public class UpdateTestActivity extends Activity {private Button button;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                button = (Button) findViewById(R.id.check);        button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {try {checkVersion();} catch (NameNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});    }        /**     * 檢查是否需要更新程式     * @throws NameNotFoundException      */    private void checkVersion() throws NameNotFoundException{    UpdateInfo updateInfo = new UpdateInfo();    URL url;try {url = new URL("http://localhost:8080/update.xml");HttpURLConnection connection = (HttpURLConnection) url.openConnection();//connection.setConnectTimeout(5000);updateInfo = ParseXmlUtils.parseXml(connection.getInputStream());} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}if(updateInfo.getVersion().equals(VersionUtil.getVersionName(this))){Toast.makeText(this, "版本相同,不需要升級!", Toast.LENGTH_SHORT).show();}else{showUpdateDialog(updateInfo);}    }private void showUpdateDialog(UpdateInfo updateInfo) {AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle("提示檢測到新版本,確定升級嗎?").setIcon(R.drawable.ask).setMessage(updateInfo.getDescription()).setPositiveButton("確定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.cancel();  }}).setNegativeButton("取消",new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.cancel();    }}).create();alertDialog.show();}}


這裡說明一下:遠程伺服器放置一個xml檔案,用來說明當前新版本的資訊。包括版本號碼,新版本功能說明,新版下載連結


xml解析工具代碼:

package com.cloay.update;import java.io.IOException;import java.io.InputStream;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;/** * 解析Xml檔案 * ParseXmlUtils.java * @author Cloay * 2011-11-7 */public class ParseXmlUtils {/** * 通過InputStream 解析檔案 * @param in * @return */public static UpdateInfo parseXml(InputStream in){UpdateInfo updateInfo = new UpdateInfo();DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();              DocumentBuilder db = null;          try {db = dbf.newDocumentBuilder();Document doc = null;    doc = db.parse(in); Element root = doc.getDocumentElement();NodeList resultNode = root.getElementsByTagName("info");    for(int i = 0; i < resultNode.getLength();i++){    Element res = (Element)resultNode.item(i);  updateInfo.setVersion(res.getElementsByTagName("version").item(0).getFirstChild().getNodeValue());updateInfo.setUrl(res.getElementsByTagName("url").item(0).getFirstChild().getNodeValue());updateInfo.setDescription(res.getElementsByTagName("description").item(0).getFirstChild().getNodeValue());}} catch (ParserConfigurationException e) {e.printStackTrace();} catch (SAXException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}      return updateInfo;}}


updateInfo實體:

package com.cloay.update;/** * 更新資訊實體類 * UpdateInfo.java * @author Cloay * 2011-11-23 */public class UpdateInfo {      private String version;    //版本號碼    private String url;  //新版本存放url路徑    private String description;   //更新說明資訊,比如新增什麼功能特性等    public String getVersion() {          return version;      }      public void setVersion(String version) {          this.version = version;      }      public String getUrl() {          return url;      }      public void setUrl(String url) {          this.url = url;      }      public String getDescription() {          return description;      }      public void setDescription(String description) {          this.description = description;      }  }  


擷取當前已安裝版本資訊:

package com.cloay.update;import android.content.Context;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.content.pm.PackageManager.NameNotFoundException;/** * 版本工具類 * VersionUtil.java * @author Cloay * 2011-11-23 */public class VersionUtil {/** * 擷取版本號碼 * @param context * 上下文 * @return * @throws NameNotFoundException  */public static String getVersionName(Context context) throws NameNotFoundException{//擷取PackageManager 執行個體PackageManager packageManager = context.getPackageManager();//獲得context所屬類的包名,0表示擷取版本資訊PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);return packageInfo.versionName;}}


其實整個過程並不是很麻煩,需要注釋的地方都已詳細注釋了,就寫那麼多。有問題請留言大家一起交流學習!

說明:轉載請註明出處!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.