Android App實現(xiàn)應(yīng)用內(nèi)部自動更新的最基本方法示例
這只是初步的實現(xiàn),并沒有加入自動編譯等功能。需要手動更改更新的xml文件和最新的apk。
共涉及到四個文件!
一、客戶端
AndroidUpdateTestActivity:程序首頁
main.xml:首頁布局
Update:更新類
softupdate_progress:更新等待界面
Updage
package majier.test; 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.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; 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 Update { private static final int DOWNLOAD = 1; private static final int DOWNLOAD_FINISH = 2; private static final int CONNECT_FAILED = 0; private static final int CONNECT_SUCCESS = 1; HashMap<String, String> mHashMap; private String mSavePath; private int progress; private boolean cancelUpdate = false; private Context mContext; private ProgressBar mProgress; private Dialog mDownloadDialog; private String mXmlPath; // 服務(wù)器更新xml存放地址 public Update(Context context, String xmlPath, String savePath) { this.mContext = context; this.mXmlPath = xmlPath; this.mSavePath = savePath; } private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case DOWNLOAD: mProgress.setProgress(progress); break; case DOWNLOAD_FINISH: installApk(); break; default: break; } }; }; /** * 檢查更新 */ public void checkUpdate() { new Thread(new Runnable() { @Override public void run() { try { URL url = new URL(mXmlPath); HttpURLConnection conn = (HttpURLConnection) url .openConnection(); conn.setConnectTimeout(5000); InputStream inStream = conn.getInputStream(); mHashMap = parseXml(inStream); Message msg = new Message(); msg.what = CONNECT_SUCCESS; handler.sendMessage(msg); } catch (Exception e) { Message msg = new Message(); msg.what = CONNECT_FAILED; handler.sendMessage(msg); } } }).run(); } /** * 訪問服務(wù)器更新XML */ Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case CONNECT_FAILED: Toast.makeText(mContext, "訪問服務(wù)器失敗!", Toast.LENGTH_SHORT).show(); break; case CONNECT_SUCCESS: if (null != mHashMap) { int serviceCode = Integer.valueOf(mHashMap.get("version")); if (serviceCode > getVersionCode(mContext)) { showNoticeDialog(); } } break; } } }; /** * 獲取程序版本號 */ private int getVersionCode(Context context) { int versionCode = 0; try { versionCode = context.getPackageManager().getPackageInfo( mContext.getPackageName(), 0).versionCode; } catch (NameNotFoundException e) { e.printStackTrace(); } return versionCode; } /** * 是否更新提示窗口 */ private void showNoticeDialog() { AlertDialog.Builder builder = new Builder(mContext); builder.setTitle("軟件更新"); builder.setMessage("檢測到新版本,是否更新?"); builder.setPositiveButton("更新", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); showDownloadDialog(); } }); builder.setNegativeButton("取消", 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("正在更新"); 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("取消下載", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); cancelUpdate = true; } }); mDownloadDialog = builder.create(); mDownloadDialog.show(); downloadApk(); } /** * 涓嬭澆apk鏂囦歡 */ private void downloadApk() { new downloadApkThread().start(); } /** * 下載程序 */ private class downloadApkThread extends Thread { @Override public void run() { try { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { 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); } private HashMap<String, String> parseXml(InputStream inStream) throws Exception { HashMap<String, String> hashMap = new HashMap<String, String>(); // 實例化一個文檔構(gòu)建器工廠 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 通過文檔構(gòu)建器工廠獲取一個文檔構(gòu)建器 DocumentBuilder builder = factory.newDocumentBuilder(); // 通過文檔通過文檔構(gòu)建器構(gòu)建一個文檔實例 Document document = builder.parse(inStream); // 獲取XML文件根節(jié)點 Element root = document.getDocumentElement(); // 獲得所有子節(jié)點 NodeList childNodes = root.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { // 遍歷子節(jié)點 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; } }
AndroidUpdateTestActivity
package majier.test; import android.app.Activity; import android.os.Bundle; import android.os.Environment; public class AndroidUpdateTestActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); update(); } private void update() { String sdpath = Environment.getExternalStorageDirectory() + "/"; String mSavePath = sdpath + "boiler/"; Update updateManager = new Update(this, "http://localhost:8011/abcd.xml", mSavePath); updateManager.checkUpdate(); } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout>
softupdate_progress.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content"> <ProgressBar android:id="@+id/update_progress" android:layout_width="fill_parent" android:layout_height="wrap_content" style="?android:attr/progressBarStyleHorizontal" /> </LinearLayout>
每次生成新的apk前,需要修改系統(tǒng)的版本號。
修改version code 和version name。上面的代碼可以看出,系統(tǒng)是根據(jù)version code來判斷是否需要更新的。version name作為一個版本名稱。
這里我建議version code從10開始,這樣方面名稱修改(1.1、1.2)。
修改完成后,生成系統(tǒng)。然后將apk文件放在服務(wù)端的文件下。
二、服務(wù)端
服務(wù)端主要是建立一個網(wǎng)址供用戶下載apk。在IIS上新建網(wǎng)站
http://localhost:8011/。將更新文件和更新的xml放在目錄下。
version.xml格式
<update> <version>12</version> <name>BoilerAndroid_1.1</name> <url>http://192.168.0.33:8011/boilerandroid.apk</url> </update>
version對應(yīng)著新程序的version code;
name隨便起名;
url對應(yīng)apk的下載路徑。
在這里有可能會遇見一個問題,訪問url路徑時IIS報錯。主要是因為IIS并不認(rèn)識apk,不知道如何處理。
這里我們在IIS中新增安卓程序的MIME類型,來使apk支持下載。
在“IIS管理器”中查看所建立的網(wǎng)站——MIME類型——添加。
文件擴(kuò)展名:.apk
MIME類型:application/vnd.android.package-archive
這樣就可以下載了。
目前只是一個簡單的自動更新程序。我們可以看出,其中版本號需要自己填寫,而且要與xml中的對應(yīng),apk需要生成后放在更新網(wǎng)址下。
這么的人為操作,很容易造成失誤。因此,接下來我們要研究下自動發(fā)布更新版本,并且版本號與svn對應(yīng),在提交svn后,自動改變程序的版本號。
- Android編程實現(xiàn)自動檢測版本及自動升級的方法
- android實現(xiàn)程序自動升級到安裝示例分享(下載android程序安裝包)
- Android編程實現(xiàn)應(yīng)用自動更新、下載、安裝的方法
- 安卓(Android)應(yīng)用版本更新方法
- Android應(yīng)用自動更新功能實現(xiàn)的方法
- Android應(yīng)用APP自動更新功能的代碼實現(xiàn)
- Android應(yīng)用強(qiáng)制更新APP的示例代碼
- Android應(yīng)用App更新實例詳解
- 非常實用的小功能 Android應(yīng)用版本的更新實例
- Android應(yīng)用更新之自動檢測版本及自動升級
相關(guān)文章
Android啟動頁設(shè)置及動態(tài)權(quán)限跳轉(zhuǎn)問題解決
在我遇到這個實際問題之前,我一直認(rèn)為啟動頁的作用是美化產(chǎn)品,提升軟件逼格。但實際上,它更重要的是起到了一個攔截器的作用,這篇文章主要介紹了Android啟動頁設(shè)置以及動態(tài)權(quán)限跳轉(zhuǎn),需要的朋友可以參考下2022-04-04Android Selector 按下修改背景和文本顏色的實現(xiàn)代碼
這篇文章主要介紹了Android Selector 按下修改背景和文本顏色的實現(xiàn)代碼,本文通過實例代碼和demo展示給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-11-11Android中轉(zhuǎn)場動畫的實現(xiàn)與兼容性處理
大家都知道Android 中的動畫有很多,除了在一個界面上使用幀動畫、屬性動畫將一個或多個 View 進(jìn)行動畫處理以外,還可以用于兩個界面之間過渡、跳轉(zhuǎn)。本文的內(nèi)容包括:Android 5.0+ 的轉(zhuǎn)場動畫和Android 4.X 模擬實現(xiàn) Android 5.0+ 轉(zhuǎn)場效果。有需要的可以參考借鑒。2016-10-10學(xué)習(xí)使用Material Design控件(一)
這篇文章主要為大家介紹了學(xué)習(xí)使用Material Design控件的詳細(xì)教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07Android Presentation雙屏異顯開發(fā)流程詳細(xì)講解
最近開發(fā)的一個項目,有兩個屏幕,需要將第二個頁面投屏到副屏上,這就需要用到Android的雙屏異顯(Presentation)技術(shù)了,研究了一下,這里做下筆記2023-01-01