我所開發應用不是面向大衆的應用,因此沒法放到應用市場去讓你們下載,而後經過應用市場更新.因此我必要作一個應用自動更新功能.可是不難,Thanks to下面這篇博客:java
Android應用自動更新功能的實現!!! android
若是你是之前沒有作過此類功能,建議你先看上面的文章.而後再來看個人.由於我也是參考了上面的實現.安全
其實這個自動更新功能大致就是兩個三個步驟:服務器
(1)檢查更新網絡
(2)下載更新app
(3)安裝更新 ide
檢查更新和下載更新其實能夠算是一步.由於都比較簡單,都是主要是下載.this
1) 當你有新的版本發佈時,在一個位置放一個更新的文件.url
裏面到少放有最新應用的版本號.而後你拿當前應用的版本號和服務器上的版本號對比,就知道要不要下載更新了.spa
2 ) 下載這個過程,對於Java來講不是什麼難事,由於Java提供了豐富的API.更況且Android內置了HttpClient可用.
3) 這個,安裝過程,其實就是使用一個打開查看此下載文件的 Intent.
這時須要考慮的是文件下載後放到哪裏,安全否.:
通常就是先檢測SD卡.而後選擇一個合適的目錄.
private void checkUpdate() { RequestFileInfo requestFileInfo = new RequestFileInfo(); requestFileInfo.fileUrl = "http://www.waitab.com/demo/demo.apk"; String status = Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED.equals(status)) { ToastUtils.showFailure(getApplicationContext(), "SDcard cannot use!"); return; } requestFileInfo.saveFilePath = Environment .getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(); requestFileInfo.saveFileName = "DiTouchClient.apk"; showHorizontalFragmentDialog(R.string.title_wait, R.string.title_download_update); new DownlaodUpdateTask().execute(requestFileInfo); }
上面的進度條顯示我已經封裝好的了.showHorizontalFragmentDialog()
顯然我使用了android-support-v4兼容包來使用Fragment的.
在進度條中有顯示,下載文件大小,已經下載了多少.速度等信息.
因爲涉及到網絡操做.因此把這整個邏輯放在AsyncTask中.
代碼以下:
private class DownlaodUpdateTask extends AsyncTask<RequestFileInfo, ProgressValue, BasicCallResult> { @Override protected BasicCallResult doInBackground(RequestFileInfo... params) { final RequestFileInfo req = params[0]; String apkFileName = ""; try { URL url = new URL(req.fileUrl); // throw MalformedURLException HttpURLConnection conn = (HttpURLConnection) url .openConnection();// throws IOException Log.i(TAG, "response code:" + conn.getResponseCode()); // 1檢查網絡鏈接性 if (HttpURLConnection.HTTP_OK != conn.getResponseCode()) { return new BasicCallResult( "Can not connect to the update Server! ", false); } int length = conn.getContentLength(); double total = StringUtils.bytes2M(length); InputStream is = conn.getInputStream(); File path = new File(req.saveFilePath); if (!path.exists()) path.mkdir(); File apkFile = new File(req.saveFilePath, req.saveFileName); apkFileName = apkFile.getAbsolutePath(); FileOutputStream fos = new FileOutputStream(apkFile); ProgressValue progressValue = new ProgressValue(0, " downlaod…"); int count = 0; long startTime, endTime; byte buffer[] = new byte[1024]; do { startTime = System.currentTimeMillis(); int numread = is.read(buffer); endTime = System.currentTimeMillis(); count += numread; if (numread <= 0) { // publish end break; } fos.write(buffer, 0, numread); double kbPerSecond = Math .ceil((endTime - startTime) / 1000f); double current = StringUtils.bytes2M(count); progressValue.message = String.format( "%.2f M/%.2f M\t\t%.2fKb/S", total, current, kbPerSecond); progressValue.progress = (int) (((float) count / length) * DialogUtil.LONG_PROGRESS_MAX); publishProgress(progressValue); } while (true); fos.flush(); fos.close(); } catch (MalformedURLException e) { e.printStackTrace(); return new BasicCallResult("Wrong url! ", false); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return new BasicCallResult("Error: " + e.getLocalizedMessage(), false); } BasicCallResult callResult = new BasicCallResult( "download finish!", true); callResult.result = apkFileName; return callResult; } @Override protected void onPostExecute(BasicCallResult result) { removeFragmentDialog(); if (result.ok) { installApk(result.result); } else { ToastUtils.showFailure(getApplicationContext(), result.message); } } @Override protected void onProgressUpdate(ProgressValue... values) { ProgressValue value = values[0]; updateProgressDialog(value); } } /** * 安裝更新APK. * * @param fileUri */ private void installApk(String fileUri) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("file://" + fileUri), "application/vnd.android.package-archive"); startActivity(intent); this.finish(); }
PS:Java中傳遞或者返回多個值,我經常使用的辦法就是將數據封裝到一個對象中去.上面用到的一些封裝對象以下:
傳遞多個值用對象是由於AsyncTask設計讓你傳遞一個對象做爲傳遞參數,因此傳遞對象也須要這樣使用.
/** * 傳遞給android 設置進度條對象 * * @author banxi1988 * */ public final class ProgressValue { /** * 須要設置的進度 */ public int progress; /** * 提示信息 */ public String message; public ProgressValue(int progress, String message) { super(); this.progress = progress; this.message = message; } }
基本的調用返回對象:
public class BasicCallResult { public String message; public boolean ok; public String result; public BasicCallResult(String message, boolean ok) { super(); this.message = message; this.ok = ok; } }
傳遞下載相關信息..
public class RequestFileInfo { public String fileUrl; public String saveFilePath; public String saveFileName; }
今天更新到這裏,有什麼問題,請指出,謝謝.