Android開發之應用程式更新實現

來源:互聯網
上載者:User

標籤:android   應用程式更新   xml   

最近給項目app做升級,對Android應用程式更新稍有研究,分享一下我的心得。

既然是更新,那麼一定是要連網和下載的,所以連網和儲存存取權限時一定要有的:

<!-- 許可權申請 -->
    <uses-permission android:name="android.permission.INTERNET" /><!-- 連網許可權 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /><!-- 儲存許可權 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

可以用xml的方式和資料庫、php等方式檢測升級版本

XML:

<?xml version="1.0" encoding="utf-8"?>
<update>
        <version>2.0<ersion>
        <description>這裡寫一些這個版本的特點</description>
        <apkurl>填寫應用下載</apkurl>
        <!--這裡的ip地址一定要寫你伺服器所在的電腦的ip地址,我們會在Security這個目錄下面放置一下new.apk的,用來更新的-->
</update>

匹配一下:

public class UpdateInfoParser {
public static UpdateInfo getUpdateInfo(InputStream is) throws Exception {
UpdateInfo info = new UpdateInfo();
XmlPullParser xmlPullParser = Xml.newPullParser();
xmlPullParser.setInput(is, "utf-8");
int type = xmlPullParser.getEventType();
while (type != XmlPullParser.END_DOCUMENT) {
switch (type) {
case XmlPullParser.START_TAG:
if (xmlPullParser.getName().equals("version")) {
info.setVersion(xmlPullParser.nextText());
} else if (xmlPullParser.getName().equals("description")) {
info.setDescription(xmlPullParser.nextText());
} else if (xmlPullParser.getName().equals("apkurl")) {
info.setUrl(xmlPullParser.nextText());
}
break;
default:
break;
}
type = xmlPullParser.next();
}
return info;
}
}

HTTP請求:

public class UpdateInfoService {
private Context context;

public UpdateInfoService(Context context) {
this.context = context;
}

public UpdateInfo getUpdateInfo(int urlId) throws Exception {
String path = context.getResources().getString(urlId);// 拿到config.xml裡面存放的地址
URL url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();// 開啟一個http連結
httpURLConnection.setConnectTimeout(5000);// 設定連結的逾時時間,現在為5秒
httpURLConnection.setRequestMethod("GET");// 佈建要求的方式
InputStream is = httpURLConnection.getInputStream();// 拿到一個輸入資料流。裡麵包涵了update.xml的資訊
return UpdateInfoParser.getUpdateInfo(is);// 解析xml
}
}

然後就可以根據與擷取到的資料相比較並且下載更新了。

其他的做法和這個類似,不過此種方式比較簡單一些,也是最頻繁的使用方式。


個人辛勤勞動成果,如有轉載,請註明出處,謝謝!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.