安卓APP採用觀察者模式實現檢測版本更新

來源:互聯網
上載者:User

標籤:des   android   style   http   os   io   使用   java   ar   

第一步:定義觀察者

public interface CheckVersionObserver {/** * 在MainActivity裡面檢測版本更新成功 * @param mainEntity */public void onCheckNewVerSuccInMain(MainEntity mainEntity);/** * 檢測新版本失敗 * @param errorCode * @param msg */public void onCheckNewVerFail(int errorCode,String msg);/** * 檢測新版本成功 * @param token * @param msg */public void onCheckNewVerSucc(CheckUpdataEntity newEntity);/** * 檢測到版本可以升級,並且能夠升級(含有記憶卡) * @param token * @param msg */public void onCheckVerCanUpdate(String promt, String versionName);/** * 檢測到版本可以升級,但不能夠升級(無記憶卡) */public void onCheckVerCanNotUpdate();/** * 下載失敗 * @param code * @param err */public void onUpdateError(String topic, String msg, String btnStr, final int type);/** * 正在更新下載 * @param totalSize * @param downSize */public void onDataUpdating(int totalSize, int downSize);}

第二步:檢測系統版本是否升級邏輯

public class CheckNewVersionLogic extends BaseLogic<CheckVersionObserver>implements UpdateDownLoadResponse {private Context mContext;private Activity mActivity;private final static int DOWNLOAD_UPDATE = 1;private final static int DOWNLOAD_UPDATING = 2;private final static int DOWNLOAD_ERROR = 3;public Handler mDownloadHandler;private String downloadUrl;private ProgressDialog mDialog = null;private int mDownFileSize = 0;private int mDownSize = 0;public CheckNewVersionLogic() {}public CheckNewVersionLogic(Context context) {this.mContext = context;mActivity = (Activity) mContext;mDownloadHandler = new DownloadHandler();}/** * 判斷檢測更新要求是否成功 *  * @param vercode */public void CheckNewVersion(final String vercode) {new BackForeTask(true) {CheckUpdataEntity result = null;@Overridepublic void onFore() {// TODO Auto-generated method stubif (result == null) {fireCheckNewVersionFail(-1, null);} else if (result.getRetcode() != 0) {fireCheckNewVersionFail(result.getRetcode(),result.getMessage());} else {fireCheckNewVersionSucc(result);}}@Overridepublic void onBack() {// TODO Auto-generated method stubresult = ProtocolImpl.getInstance().checkVersion(vercode);}};}/** * 主介面檢查更新 * @param token * @param firstopen * @param mobiletype * @param mobilesys * @param vercode */public void CheckNewVerInMain(final int firstopen,final String mobiletype, final String mobilesys, final String vercode) {new BackForeTask(true) {MainEntity result = null;@Overridepublic void onFore() {// TODO Auto-generated method stubif (result == null) {fireCheckNewVersionFail(-1, null);} else if (result.getRetcode() != 0) {fireCheckNewVersionFail(result.getRetcode(),result.getMessage());} else {fireCheckNewVerSuccInMain(result);}}@Overridepublic void onBack() {// TODO Auto-generated method stubresult = ProtocolImpl.getInstance().checkVerInMain(firstopen, mobiletype, mobilesys, vercode);}};}private void fireCheckNewVerSuccInMain(MainEntity mainEntity){List<CheckVersionObserver> tmpList = getObservers();for (CheckVersionObserver observer : tmpList) {observer.onCheckNewVerSuccInMain(mainEntity);}}/** * 版本更新要求失敗 *  * @param errorCode * @param msg */private void fireCheckNewVersionFail(int errorCode, String msg) {List<CheckVersionObserver> tmpList = getObservers();for (CheckVersionObserver observer : tmpList) {observer.onCheckNewVerFail(errorCode, msg);}}/** * 版本更新要求成功 *  * @param newEntity */private void fireCheckNewVersionSucc(CheckUpdataEntity newEntity) {List<CheckVersionObserver> tmpList = getObservers();for (CheckVersionObserver observer : tmpList) {observer.onCheckNewVerSucc(newEntity);}}/** * 檢測到版本可以升級,並且能夠升級(含有記憶卡) *  * @param promt * @param versionName */private void fireCheckVerCanUpdate(String promt, String versionName) {List<CheckVersionObserver> tmpList = getObservers();for (CheckVersionObserver observer : tmpList) {observer.onCheckVerCanUpdate(promt, versionName);}}/** * 檢測到版本可以升級,但不能夠升級(無記憶卡) */private void fireCheckVerCanNotUpdate() {List<CheckVersionObserver> tmpList = getObservers();for (CheckVersionObserver observer : tmpList) {observer.onCheckVerCanNotUpdate();}}/** * 下載失敗 *  * @param code * @param err */private void fireOnError(String topic, String msg, String btnStr,final int type) {List<CheckVersionObserver> tmpList = getObservers();for (CheckVersionObserver observer : tmpList) {observer.onUpdateError(topic, msg, btnStr, type);}}/** * 正在下載 *  * @param totalSize * @param downSize */private void fireOnDataUpdating(int downFileSize, int downSize) {List<CheckVersionObserver> tmpList = getObservers();for (CheckVersionObserver observer : tmpList) {observer.onDataUpdating(downFileSize, downSize);}}/** * 下載更新 */public void downloadUpdate() {mDownloadHandler.sendEmptyMessage(DOWNLOAD_UPDATE);}/** * 正在下載更新 *  * @param totalSize * @param downSize */public void downloadUpdating(int totalSize, int downSize) {mDownFileSize = totalSize;mDownSize = downSize;mDownloadHandler.sendEmptyMessage(DOWNLOAD_UPDATING);}/** * 下載失敗 */public void downloadError() {mDownloadHandler.sendEmptyMessage(DOWNLOAD_ERROR);}/*** * 選擇是否更新版本 */public void checkVersion(int serverVerCode, String promt, String versionName, String url) {Log.i("ciyunupdate", serverVerCode + "");System.out.println("serverVerCode" + serverVerCode);int appVerCode = 1;try {appVerCode = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;Log.i("ciyunupdate", appVerCode + "");System.out.println("appVerCode" + appVerCode);} catch (NameNotFoundException e) {e.printStackTrace();}if (serverVerCode > appVerCode) {if (!FileUtil.isSdCardExist()) {/* * showDialog(mContext.getString(R.string.str_version_update), * mContext.getResources().getString(R.string.no_sdcard), * mContext.getResources().getString(R.string.sure), 0); */fireCheckVerCanNotUpdate();} else {// popUpdateDlg(promt,versionName);downloadUrl = url;fireCheckVerCanUpdate(promt, versionName);}}}/** *  * @Description:下載更新處理器 * @author: * @see: * @since: * @copyright © ciyun.cn * @Date:2014年8月12日 */private class DownloadHandler extends Handler {/** * {@inheritDoc} *  * @see android.os.Handler#handleMessage(android.os.Message) */@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);switch (msg.what) {case DOWNLOAD_UPDATE: {new Thread() {@Overridepublic void run() {super.run();if (Utils.isExternalStorageRemovable()) {FileUtil.createFileEx(HealthApplication.UPDATAFILENAME);HttpPostEngine service = new HttpPostEngine();service.downloadUpdateFile(CheckNewVersionLogic.this,downloadUrl,FileUtil.updateFile.getPath());}}}.start();}break;case DOWNLOAD_UPDATING:fireOnDataUpdating(mDownFileSize, mDownSize);break;case DOWNLOAD_ERROR:fireOnError(mContext.getString(R.string.str_version_update),mContext.getString(R.string.str_download_err),mContext.getResources().getString(R.string.sure), 0);break;}}}@Overridepublic void OnError(int code, String err) {// TODO Auto-generated method stubLog.v("update", code + "/" + err);if (mDialog != null && mDialog.isShowing()) {mDialog.dismiss();}mDownloadHandler.sendEmptyMessage(DOWNLOAD_ERROR);}@Overridepublic void OnDataUpdated(int totalSize, int downSize) {// TODO Auto-generated method stubmDownFileSize = totalSize;mDownSize = downSize;mDownloadHandler.sendEmptyMessage(DOWNLOAD_UPDATING);}@Overridepublic void OnUpdatedFinish() {// TODO Auto-generated method stubUri uri = Uri.fromFile(FileUtil.updateFile);Intent intent = new Intent(Intent.ACTION_VIEW);intent.setDataAndType(uri, "application/vnd.android.package-archive");mActivity.startActivity(intent);}}

第三步:在主介面按鈕事件裡面寫如下代碼:
CheckNewVersionLogic checkNewVersionLogic = new CheckNewVersionLogic(AboutAppActivity.this);checkNewVersionLogic.CheckNewVersion(verCode + "");

第四步:主介面類要實現CheckVersionObserver,並實現如下方法:

void showDialog(String topic, String msg, String btnStr, final int type) {AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setIcon(android.R.drawable.ic_dialog_info);builder.setTitle(topic);builder.setMessage(msg);builder.setNegativeButton(btnStr,new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {dialog.dismiss();if (type == 1) {AboutAppActivity.this.finish();} else {}}});builder.setCancelable(false);builder.create().show();}private void popUpdatingDlg(long totalSize) {if (mDialog == null) {mDialog = new ProgressDialog(this);mDialog.setMax(100);String size = (totalSize*0.000001 + "").substring(0, 4);mDialog.setTitle(getResources().getString(R.string.now_loading_new_version)+size+"M)");mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);mDialog.setCanceledOnTouchOutside(false);mDialog.setOnKeyListener(new OnKeyListener() {@Overridepublic boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {if ((keyCode == KeyEvent.KEYCODE_SEARCH)|| (keyCode == KeyEvent.KEYCODE_BACK)) {return true;}return false;}});mDialog.setCancelable(false);mDialog.show();}}@Overridepublic void onCheckVerCanUpdate(String promt, String versionName) {// TODO Auto-generated method stubpopUpdateDlg(promt,versionName);}@Overridepublic void onCheckVerCanNotUpdate() {// TODO Auto-generated method stubshowDialog(getString(R.string.str_version_update),getResources().getString(R.string.no_sdcard), getResources().getString(R.string.sure), 0);}@Overridepublic void onUpdateError(String topic, String msg, String btnStr, int type) {// TODO Auto-generated method stubshowDialog(topic,msg, btnStr, type);}@Overridepublic void onDataUpdating(int totalSize, int downSize) {// TODO Auto-generated method stubpopUpdatingDlg(totalSize);if (mDialog != null && mDialog.isShowing()) {if (downSize < totalSize) {mDialog.setProgress(downSize*100/totalSize);} else {mDialog.dismiss();}}}@Overridepublic void onCheckNewVerFail(int errorCode, String msg) {// TODO Auto-generated method stubhaloToast.dismissWaitDialog();//關閉提示框if(!TextUtils.isEmpty(msg))Toast.makeText(this, msg, 3000).show() ;if(errorCode == 200){Intent intent = new Intent(AboutAppActivity.this,LoginActivity.class) ;startActivity(intent);}if(TextUtils.isEmpty(msg)){Toast.makeText(this, R.string.str_network_error_msg, 3000).show();}}@Overridepublic void onCheckNewVerSucc(CheckUpdataEntity newEntity) {// TODO Auto-generated method stubhaloToast.dismissWaitDialog();if (newEntity.getRetcode() == 0) {HealthApplication.mUserCache.setToken(newEntity.getToken());if (newEntity.getData()!=null) {int serverVerCode = newEntity.getData().getVercode();String prompt = newEntity.getData().getMessage();String verName = newEntity.getData().getVername();checkNewVersionLogic.checkVersion(serverVerCode, prompt, verName, newEntity.getData().getAppurl());}}}@Overridepublic void onCheckNewVerSuccInMain(MainEntity mainEntity) {// TODO Auto-generated method stub}

第五步:用到的一些網路方法:

/** * 檢測系統版本升級 * @param vercode * @return */public CheckUpdataEntity checkVersion(String vercode){JSONObject j = HttpJsonRequesProxy.getInstance().getCheckVerReques(vercode);String jsonData=null;try {jsonData = httpUtil.sendDataToServer(LoveHealthConstant.HOSTURL, j.toString());} catch (Exception e) {e.printStackTrace();}if(jsonData==null){return null;}return JsonUtil.parse(jsonData, CheckUpdataEntity.class);}/** * 主介面檢測系統版本是否升級 * @param token * @param firstopen * @param mobiletype * @param mobilesys * @param vercode * @return */public MainEntity checkVerInMain(int firstopen,String mobiletype, String mobilesys, String vercode) {JSONObject j = HttpJsonRequesProxy.getInstance().getHomePageReques(firstopen, mobiletype, mobilesys, vercode);String jsonData=null;try {jsonData = httpUtil.sendDataToServer(LoveHealthConstant.HOSTURL, j.toString());} catch (Exception e) {e.printStackTrace();}if(jsonData==null){return null;}return JsonUtil.parse(jsonData, MainEntity.class);}

/** * 版本更新 *  * @param token * @param vercode * @return */public JSONObject getCheckVerReques(String vercode) {JSONObject title = getContextJsonObj("CheckUp");try {// 另外一個Json對象需要建立JSONObject mQrInfo = new JSONObject();mQrInfo.put("vercode", vercode);// 將使用者和碼值添加到整個Json中title.put("data", mQrInfo);} catch (JSONException e) {// 鍵為null或使用json不支援的數字格式(NaN, infinities)throw new RuntimeException(e);}return title;}

/** * 首頁 *  * @param token * @param firstopen * @param mobiletype * @param mobilesys * @param vercode * @return */public JSONObject getHomePageReques(int firstopen,String mobiletype, String mobilesys, String vercode) {JSONObject title = getContextJsonObj("HomePage");try {// 另外一個Json對象需要建立JSONObject mQrInfo = new JSONObject();mQrInfo.put("firstopen", firstopen);mQrInfo.put("mobiletype", mobiletype);mQrInfo.put("mobilesys", mobilesys);mQrInfo.put("vercode", vercode);// 將使用者和碼值添加到整個Json中title.put("data", mQrInfo);} catch (JSONException e) {// 鍵為null或使用json不支援的數字格式(NaN, infinities)throw new RuntimeException(e);}return title;}

public String sendDataToServer(String url, String body) throws Exception {HttpPost httpPost = new HttpPost(url);ByteArrayEntity postdata = new ByteArrayEntity(body.getBytes());httpPost.setEntity(postdata);int res = 0;HttpParams httpParameters = new BasicHttpParams();HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT);HttpConnectionParams.setSoTimeout(httpParameters, TIME_OUT);DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);HttpResponse httpResponse = httpClient.execute(httpPost);res = httpResponse.getStatusLine().getStatusCode();if (res == 200) {String result = EntityUtils.toString(httpResponse.getEntity());XLog.d("result==", result);return result;}return null;}






安卓APP採用觀察者模式實現檢測版本更新

聯繫我們

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