安卓APP采用观察者模式实现检测版本更新

第一步:定义观察者

  1. public interface CheckVersionObserver { 
  2.  
  3.  
  4.     /**
  5.      * 在MainActivity里面检测版本更新成功
  6.      * @param mainEntity
  7.      */ 
  8.     public void onCheckNewVerSuccInMain(MainEntity mainEntity); 
  9.      
  10.     /**
  11.      * 检测新版本失败
  12.      * @param errorCode
  13.      * @param msg
  14.      */ 
  15.     public void onCheckNewVerFail(int errorCode,String msg); 
  16.      
  17.     /**
  18.      * 检测新版本成功
  19.      * @param token
  20.      * @param msg
  21.      */ 
  22.     public void onCheckNewVerSucc(CheckUpdataEntity newEntity); 
  23.      
  24.     /**
  25.      * 检测到版本可以升级,并且能够升级(含有内存卡)
  26.      * @param token
  27.      * @param msg
  28.      */ 
  29.     public void onCheckVerCanUpdate(String promt, String versionName); 
  30.     /**
  31.      * 检测到版本可以升级,但不能够升级(无内存卡)
  32.      */ 
  33.     public void onCheckVerCanNotUpdate(); 
  34.     /**
  35.      * 下载失败
  36.      * @param code
  37.      * @param err
  38.      */ 
  39.     public void onUpdateError(String topic, String msg, String btnStr, final int type); 
  40.     /**
  41.      * 正在更新下载
  42.      * @param totalSize
  43.      * @param downSize
  44.      */ 
  45.     public void onDataUpdating(int totalSize, int downSize); 
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);
}

第二步:检测系统版本是否升级逻辑

  1. public class CheckNewVersionLogic extends BaseLogic<CheckVersionObserver> 
  2.         implements UpdateDownLoadResponse { 
  3.  
  4.     private Context mContext; 
  5.     private Activity mActivity; 
  6.  
  7.     private final static int DOWNLOAD_UPDATE = 1; 
  8.     private final static int DOWNLOAD_UPDATING = 2; 
  9.     private final static int DOWNLOAD_ERROR = 3; 
  10.  
  11.     public Handler mDownloadHandler; 
  12.     private String downloadUrl; 
  13.  
  14.     private ProgressDialog mDialog = null; 
  15.     private int mDownFileSize = 0; 
  16.     private int mDownSize = 0; 
  17.  
  18.     public CheckNewVersionLogic() { 
  19.     } 
  20.  
  21.     public CheckNewVersionLogic(Context context) { 
  22.         this.mContext = context; 
  23.         mActivity = (Activity) mContext; 
  24.         mDownloadHandler = new DownloadHandler(); 
  25.     } 
  26.  
  27.     /**
  28.      * 判断检测更新请求是否成功
  29.      *
  30.      * @param vercode
  31.      */ 
  32.     public void CheckNewVersion(final String vercode) { 
  33.         new BackForeTask(true) { 
  34.             CheckUpdataEntity result = null; 
  35.  
  36.             @Override 
  37.             public void onFore() { 
  38.                 // TODO Auto-generated method stub 
  39.  
  40.                 if (result == null) { 
  41.                     fireCheckNewVersionFail(-1, null); 
  42.                 } else if (result.getRetcode() != 0) { 
  43.                     fireCheckNewVersionFail(result.getRetcode(), 
  44.                             result.getMessage()); 
  45.                 } else { 
  46.                     fireCheckNewVersionSucc(result); 
  47.                 } 
  48.  
  49.             } 
  50.  
  51.             @Override 
  52.             public void onBack() { 
  53.                 // TODO Auto-generated method stub 
  54.                 result = ProtocolImpl.getInstance().checkVersion(vercode); 
  55.  
  56.             } 
  57.         }; 
  58.  
  59.     } 
  60.  
  61.     /**
  62.      * 主界面检查更新
  63.      * @param token
  64.      * @param firstopen
  65.      * @param mobiletype
  66.      * @param mobilesys
  67.      * @param vercode
  68.      */ 
  69.     public void CheckNewVerInMain(final int firstopen, 
  70.             final String mobiletype, final String mobilesys, final String vercode) { 
  71.         new BackForeTask(true) { 
  72.  
  73.             MainEntity result = null; 
  74.  
  75.             @Override 
  76.             public void onFore() { 
  77.                 // TODO Auto-generated method stub 
  78.  
  79.                 if (result == null) { 
  80.                     fireCheckNewVersionFail(-1, null); 
  81.                 } else if (result.getRetcode() != 0) { 
  82.                     fireCheckNewVersionFail(result.getRetcode(), 
  83.                             result.getMessage()); 
  84.                 } else { 
  85.                     fireCheckNewVerSuccInMain(result); 
  86.                 } 
  87.                  
  88.             } 
  89.  
  90.             @Override 
  91.             public void onBack() { 
  92.                 // TODO Auto-generated method stub 
  93.                 result = ProtocolImpl.getInstance().checkVerInMain(firstopen, mobiletype, mobilesys, vercode); 
  94.             } 
  95.         }; 
  96.     } 
  97.      
  98.     private void fireCheckNewVerSuccInMain(MainEntity mainEntity){ 
  99.         List<CheckVersionObserver> tmpList = getObservers(); 
  100.         for (CheckVersionObserver observer : tmpList) { 
  101.             observer.onCheckNewVerSuccInMain(mainEntity); 
  102.         } 
  103.     } 
  104.      
  105.  
  106.     /**
  107.      * 版本更新请求失败
  108.      *
  109.      * @param errorCode
  110.      * @param msg
  111.      */ 
  112.     private void fireCheckNewVersionFail(int errorCode, String msg) { 
  113.         List<CheckVersionObserver> tmpList = getObservers(); 
  114.         for (CheckVersionObserver observer : tmpList) { 
  115.             observer.onCheckNewVerFail(errorCode, msg); 
  116.         } 
  117.     } 
  118.  
  119.     /**
  120.      * 版本更新请求成功
  121.      *
  122.      * @param newEntity
  123.      */ 
  124.     private void fireCheckNewVersionSucc(CheckUpdataEntity newEntity) { 
  125.         List<CheckVersionObserver> tmpList = getObservers(); 
  126.         for (CheckVersionObserver observer : tmpList) { 
  127.             observer.onCheckNewVerSucc(newEntity); 
  128.         } 
  129.     } 
  130.  
  131.     /**
  132.      * 检测到版本可以升级,并且能够升级(含有内存卡)
  133.      *
  134.      * @param promt
  135.      * @param versionName
  136.      */ 
  137.     private void fireCheckVerCanUpdate(String promt, String versionName) { 
  138.         List<CheckVersionObserver> tmpList = getObservers(); 
  139.         for (CheckVersionObserver observer : tmpList) { 
  140.             observer.onCheckVerCanUpdate(promt, versionName); 
  141.         } 
  142.     } 
  143.  
  144.     /**
  145.      * 检测到版本可以升级,但不能够升级(无内存卡)
  146.      */ 
  147.     private void fireCheckVerCanNotUpdate() { 
  148.         List<CheckVersionObserver> tmpList = getObservers(); 
  149.         for (CheckVersionObserver observer : tmpList) { 
  150.             observer.onCheckVerCanNotUpdate(); 
  151.         } 
  152.     } 
  153.  
  154.     /**
  155.      * 下载失败
  156.      *
  157.      * @param code
  158.      * @param err
  159.      */ 
  160.     private void fireOnError(String topic, String msg, String btnStr, 
  161.             final int type) { 
  162.         List<CheckVersionObserver> tmpList = getObservers(); 
  163.         for (CheckVersionObserver observer : tmpList) { 
  164.             observer.onUpdateError(topic, msg, btnStr, type); 
  165.         } 
  166.     } 
  167.  
  168.     /**
  169.      * 正在下载
  170.      *
  171.      * @param totalSize
  172.      * @param downSize
  173.      */ 
  174.     private void fireOnDataUpdating(int downFileSize, int downSize) { 
  175.         List<CheckVersionObserver> tmpList = getObservers(); 
  176.         for (CheckVersionObserver observer : tmpList) { 
  177.             observer.onDataUpdating(downFileSize, downSize); 
  178.         } 
  179.     } 
  180.  
  181.     /**
  182.      * 下载更新
  183.      */ 
  184.     public void downloadUpdate() { 
  185.         mDownloadHandler.sendEmptyMessage(DOWNLOAD_UPDATE); 
  186.     } 
  187.  
  188.     /**
  189.      * 正在下载更新
  190.      *
  191.      * @param totalSize
  192.      * @param downSize
  193.      */ 
  194.     public void downloadUpdating(int totalSize, int downSize) { 
  195.         mDownFileSize = totalSize; 
  196.         mDownSize = downSize; 
  197.         mDownloadHandler.sendEmptyMessage(DOWNLOAD_UPDATING); 
  198.     } 
  199.  
  200.     /**
  201.      * 下载失败
  202.      */ 
  203.     public void downloadError() { 
  204.         mDownloadHandler.sendEmptyMessage(DOWNLOAD_ERROR); 
  205.     } 
  206.  
  207.     /***
  208.      * 选择是否更新版本
  209.      */ 
  210.     public void checkVersion(int serverVerCode, String promt, String versionName, String url) { 
  211.  
  212.         Log.i("ciyunupdate", serverVerCode + ""); 
  213.         System.out.println("serverVerCode" + serverVerCode); 
  214.  
  215.         int appVerCode = 1; 
  216.         try { 
  217.             appVerCode = mContext.getPackageManager().getPackageInfo( 
  218.                     mContext.getPackageName(), 0).versionCode; 
  219.  
  220.             Log.i("ciyunupdate", appVerCode + ""); 
  221.             System.out.println("appVerCode" + appVerCode); 
  222.  
  223.         } catch (NameNotFoundException e) { 
  224.             e.printStackTrace(); 
  225.         } 
  226.         if (serverVerCode > appVerCode) { 
  227.             if (!FileUtil.isSdCardExist()) { 
  228.                 /*
  229.                  * showDialog(mContext.getString(R.string.str_version_update),
  230.                  * mContext.getResources().getString(R.string.no_sdcard),
  231.                  * mContext.getResources().getString(R.string.sure), 0);
  232.                  */ 
  233.                 fireCheckVerCanNotUpdate(); 
  234.             } else { 
  235.                 // popUpdateDlg(promt,versionName); 
  236.                 downloadUrl = url; 
  237.                 fireCheckVerCanUpdate(promt, versionName); 
  238.             } 
  239.         } 
  240.  
  241.     } 
  242.  
  243.     /**
  244.      *
  245.      * @Description:下载更新处理器
  246.      * @author:
  247.      * @see:
  248.      * @since:
  249.      * @copyright © ciyun.cn
  250.      * @Date:2014年8月12日
  251.      */ 
  252.     private class DownloadHandler extends Handler { 
  253.         /**
  254.          * {@inheritDoc}
  255.          *
  256.          * @see android.os.Handler#handleMessage(android.os.Message)
  257.          */ 
  258.         @Override 
  259.         public void handleMessage(Message msg) { 
  260.             super.handleMessage(msg); 
  261.             switch (msg.what) { 
  262.             case DOWNLOAD_UPDATE: { 
  263.                 new Thread() { 
  264.                     @Override 
  265.                     public void run() { 
  266.                         super.run(); 
  267.                         if (Utils.isExternalStorageRemovable()) { 
  268.                             FileUtil.createFileEx(HealthApplication.UPDATAFILENAME); 
  269.                             HttpPostEngine service = new HttpPostEngine(); 
  270.  
  271.                             service.downloadUpdateFile( 
  272.                                     CheckNewVersionLogic.this, 
  273.                                     downloadUrl, 
  274.                                     FileUtil.updateFile.getPath()); 
  275.                         } 
  276.                     } 
  277.                 }.start(); 
  278.             } 
  279.                 break; 
  280.             case DOWNLOAD_UPDATING: 
  281.                 fireOnDataUpdating(mDownFileSize, mDownSize); 
  282.                 break; 
  283.             case DOWNLOAD_ERROR: 
  284.                 fireOnError( 
  285.                         mContext.getString(R.string.str_version_update), 
  286.                         mContext.getString(R.string.str_download_err), 
  287.                         mContext.getResources().getString(R.string.sure), 0); 
  288.                 break; 
  289.             } 
  290.         } 
  291.     } 
  292.  
  293.     @Override 
  294.     public void OnError(int code, String err) { 
  295.         // TODO Auto-generated method stub 
  296.         Log.v("update", code + "/" + err); 
  297.         if (mDialog != null && mDialog.isShowing()) { 
  298.             mDialog.dismiss(); 
  299.         } 
  300.         mDownloadHandler.sendEmptyMessage(DOWNLOAD_ERROR); 
  301.     } 
  302.  
  303.     @Override 
  304.     public void OnDataUpdated(int totalSize, int downSize) { 
  305.         // TODO Auto-generated method stub 
  306.         mDownFileSize = totalSize; 
  307.         mDownSize = downSize; 
  308.         mDownloadHandler.sendEmptyMessage(DOWNLOAD_UPDATING); 
  309.     } 
  310.  
  311.     @Override 
  312.     public void OnUpdatedFinish() { 
  313.         // TODO Auto-generated method stub 
  314.         Uri uri = Uri.fromFile(FileUtil.updateFile); 
  315.         Intent intent = new Intent(Intent.ACTION_VIEW); 
  316.         intent.setDataAndType(uri, "application/vnd.android.package-archive"); 
  317.         mActivity.startActivity(intent); 
  318.     } 
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;

			@Override
			public void onFore() {
				// TODO Auto-generated method stub

				if (result == null) {
					fireCheckNewVersionFail(-1, null);
				} else if (result.getRetcode() != 0) {
					fireCheckNewVersionFail(result.getRetcode(),
							result.getMessage());
				} else {
					fireCheckNewVersionSucc(result);
				}

			}

			@Override
			public void onBack() {
				// TODO Auto-generated method stub
				result = 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;

			@Override
			public void onFore() {
				// TODO Auto-generated method stub

				if (result == null) {
					fireCheckNewVersionFail(-1, null);
				} else if (result.getRetcode() != 0) {
					fireCheckNewVersionFail(result.getRetcode(),
							result.getMessage());
				} else {
					fireCheckNewVerSuccInMain(result);
				}
				
			}

			@Override
			public void onBack() {
				// TODO Auto-generated method stub
				result = 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)
		 */
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case DOWNLOAD_UPDATE: {
				new Thread() {
					@Override
					public 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;
			}
		}
	}

	@Override
	public void OnError(int code, String err) {
		// TODO Auto-generated method stub
		Log.v("update", code + "/" + err);
		if (mDialog != null && mDialog.isShowing()) {
			mDialog.dismiss();
		}
		mDownloadHandler.sendEmptyMessage(DOWNLOAD_ERROR);
	}

	@Override
	public void OnDataUpdated(int totalSize, int downSize) {
		// TODO Auto-generated method stub
		mDownFileSize = totalSize;
		mDownSize = downSize;
		mDownloadHandler.sendEmptyMessage(DOWNLOAD_UPDATING);
	}

	@Override
	public void OnUpdatedFinish() {
		// TODO Auto-generated method stub
		Uri uri = Uri.fromFile(FileUtil.updateFile);
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		mActivity.startActivity(intent);
	}
}

第三步:在主界面按钮事件里面写如下代码:
  1. CheckNewVersionLogic checkNewVersionLogic = new CheckNewVersionLogic(AboutAppActivity.this); 
  2. checkNewVersionLogic.CheckNewVersion(verCode + ""); 
CheckNewVersionLogic checkNewVersionLogic = new CheckNewVersionLogic(AboutAppActivity.this);
checkNewVersionLogic.CheckNewVersion(verCode + "");

第四步:主界面类要实现CheckVersionObserver,并实现如下方法:

  1. void showDialog(String topic, String msg, String btnStr, final int type) { 
  2.         AlertDialog.Builder builder = new AlertDialog.Builder(this); 
  3.         builder.setIcon(android.R.drawable.ic_dialog_info); 
  4.         builder.setTitle(topic); 
  5.         builder.setMessage(msg); 
  6.  
  7.         builder.setNegativeButton(btnStr, 
  8.                 new DialogInterface.OnClickListener() { 
  9.                     public void onClick(DialogInterface dialog, int which) { 
  10.                         dialog.dismiss(); 
  11.                         if (type == 1) { 
  12.                             AboutAppActivity.this.finish(); 
  13.                         } else { 
  14.                              
  15.                         } 
  16.                     } 
  17.                 }); 
  18.  
  19.         builder.setCancelable(false); 
  20.         builder.create().show(); 
  21.     } 
  22.     private void popUpdatingDlg(long totalSize) { 
  23.         if (mDialog == null) { 
  24.             mDialog = new ProgressDialog(this); 
  25.             mDialog.setMax(100); 
  26.             String size = (totalSize*0.000001 + "").substring(0, 4); 
  27.             mDialog.setTitle(getResources().getString(R.string.now_loading_new_version)+size+"M)"); 
  28.             mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
  29.             mDialog.setCanceledOnTouchOutside(false); 
  30.             mDialog.setOnKeyListener(new OnKeyListener() { 
  31.  
  32.                 @Override 
  33.                 public boolean onKey(DialogInterface dialog, int keyCode, 
  34.                         KeyEvent event) { 
  35.                     if ((keyCode == KeyEvent.KEYCODE_SEARCH) 
  36.                             || (keyCode == KeyEvent.KEYCODE_BACK)) { 
  37.                         return true; 
  38.                     } 
  39.                     return false; 
  40.                 } 
  41.             }); 
  42.             mDialog.setCancelable(false); 
  43.             mDialog.show(); 
  44.         } 
  45.     } 
  46.  
  47.     @Override 
  48.     public void onCheckVerCanUpdate(String promt, String versionName) { 
  49.         // TODO Auto-generated method stub 
  50.         popUpdateDlg(promt,versionName); 
  51.     } 
  52.  
  53.     @Override 
  54.     public void onCheckVerCanNotUpdate() { 
  55.         // TODO Auto-generated method stub 
  56.         showDialog(getString(R.string.str_version_update), 
  57.                 getResources().getString(R.string.no_sdcard), getResources().getString(R.string.sure), 0); 
  58.     } 
  59.  
  60.     @Override 
  61.     public void onUpdateError(String topic, String msg, String btnStr, int type) { 
  62.         // TODO Auto-generated method stub 
  63.         showDialog(topic,msg, btnStr, type); 
  64.     } 
  65.  
  66.     @Override 
  67.     public void onDataUpdating(int totalSize, int downSize) { 
  68.         // TODO Auto-generated method stub 
  69.         popUpdatingDlg(totalSize); 
  70.         if (mDialog != null && mDialog.isShowing()) { 
  71.             if (downSize < totalSize) { 
  72.                 mDialog.setProgress(downSize*100/totalSize); 
  73.             } else { 
  74.                 mDialog.dismiss(); 
  75.             } 
  76.         } 
  77.     } 
  78.  
  79.     @Override 
  80.     public void onCheckNewVerFail(int errorCode, String msg) { 
  81.         // TODO Auto-generated method stub 
  82.          
  83.         haloToast.dismissWaitDialog();//关闭提示框 
  84.          
  85.         if(!TextUtils.isEmpty(msg)) 
  86.             Toast.makeText(this, msg, 3000).show() ; 
  87.         if(errorCode == 200){            
  88.             Intent intent = new Intent(AboutAppActivity.this,LoginActivity.class) ; 
  89.             startActivity(intent); 
  90.         } 
  91.          
  92.         if(TextUtils.isEmpty(msg)){ 
  93.             Toast.makeText(this, R.string.str_network_error_msg, 3000).show(); 
  94.         } 
  95.          
  96.     } 
  97.  
  98.     @Override 
  99.     public void onCheckNewVerSucc(CheckUpdataEntity newEntity) { 
  100.         // TODO Auto-generated method stub 
  101.  
  102.         haloToast.dismissWaitDialog(); 
  103.          
  104.         if (newEntity.getRetcode() == 0) { 
  105.             HealthApplication.mUserCache.setToken(newEntity.getToken()); 
  106.              
  107.             if (newEntity.getData()!=null) { 
  108.                 int serverVerCode = newEntity.getData().getVercode(); 
  109.                 String prompt = newEntity.getData().getMessage(); 
  110.                 String verName = newEntity.getData().getVername(); 
  111.                 checkNewVersionLogic.checkVersion(serverVerCode, prompt, verName, newEntity.getData().getAppurl()); 
  112.             } 
  113.         } 
  114.     } 
  115.  
  116.     @Override 
  117.     public void onCheckNewVerSuccInMain(MainEntity mainEntity) { 
  118.         // TODO Auto-generated method stub 
  119.          
  120.     } 
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() {

				@Override
				public 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();
		}
	}

	@Override
	public void onCheckVerCanUpdate(String promt, String versionName) {
		// TODO Auto-generated method stub
		popUpdateDlg(promt,versionName);
	}

	@Override
	public void onCheckVerCanNotUpdate() {
		// TODO Auto-generated method stub
		showDialog(getString(R.string.str_version_update),
				getResources().getString(R.string.no_sdcard), getResources().getString(R.string.sure), 0);
	}

	@Override
	public void onUpdateError(String topic, String msg, String btnStr, int type) {
		// TODO Auto-generated method stub
		showDialog(topic,msg, btnStr, type);
	}

	@Override
	public void onDataUpdating(int totalSize, int downSize) {
		// TODO Auto-generated method stub
		popUpdatingDlg(totalSize);
		if (mDialog != null && mDialog.isShowing()) {
			if (downSize < totalSize) {
				mDialog.setProgress(downSize*100/totalSize);
			} else {
				mDialog.dismiss();
			}
		}
	}

	@Override
	public void onCheckNewVerFail(int errorCode, String msg) {
		// TODO Auto-generated method stub
		
		haloToast.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();
		}
		
	}

	@Override
	public void onCheckNewVerSucc(CheckUpdataEntity newEntity) {
		// TODO Auto-generated method stub

		haloToast.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());
			}
		}
	}

	@Override
	public void onCheckNewVerSuccInMain(MainEntity mainEntity) {
		// TODO Auto-generated method stub
		
	}

第五步:用到的一些网络方法:

  1. /**
  2.      * 检测系统版本升级
  3.      * @param vercode
  4.      * @return
  5.      */ 
  6.     public CheckUpdataEntity checkVersion(String vercode){ 
  7.          
  8.         JSONObject j = HttpJsonRequesProxy.getInstance().getCheckVerReques(vercode); 
  9.         String jsonData=null; 
  10.         try { 
  11.             jsonData = httpUtil.sendDataToServer(LoveHealthConstant.HOSTURL, j.toString()); 
  12.         } catch (Exception e) { 
  13.             e.printStackTrace(); 
  14.         } 
  15.          
  16.         if(jsonData==null){ 
  17.             return null; 
  18.         } 
  19.          
  20.         return JsonUtil.parse(jsonData, CheckUpdataEntity.class);        
  21.     } 
  22.  
  23.     /**
  24.      * 主界面检测系统版本是否升级
  25.      * @param token
  26.      * @param firstopen
  27.      * @param mobiletype
  28.      * @param mobilesys
  29.      * @param vercode
  30.      * @return
  31.      */ 
  32.     public MainEntity checkVerInMain(int firstopen, 
  33.             String mobiletype, String mobilesys, String vercode) { 
  34.         JSONObject j = HttpJsonRequesProxy.getInstance().getHomePageReques(firstopen, mobiletype, mobilesys, vercode); 
  35.         String jsonData=null; 
  36.         try { 
  37.             jsonData = httpUtil.sendDataToServer(LoveHealthConstant.HOSTURL, j.toString()); 
  38.         } catch (Exception e) { 
  39.             e.printStackTrace(); 
  40.         } 
  41.          
  42.         if(jsonData==null){ 
  43.             return null; 
  44.         } 
  45.          
  46.         return JsonUtil.parse(jsonData, MainEntity.class);       
  47.     } 
/**
	 * 检测系统版本升级
	 * @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);		
	}

  1. /**
  2.      * 版本更新
  3.      *
  4.      * @param token
  5.      * @param vercode
  6.      * @return
  7.      */ 
  8.     public JSONObject getCheckVerReques(String vercode) { 
  9.         JSONObject title = getContextJsonObj("CheckUp"); 
  10.         try { 
  11.             // 另外一个Json对象需要新建 
  12.             JSONObject mQrInfo = new JSONObject(); 
  13.             mQrInfo.put("vercode", vercode); 
  14.             // 将用户和码值添加到整个Json中 
  15.             title.put("data", mQrInfo); 
  16.  
  17.         } catch (JSONException e) { 
  18.             // 键为null或使用json不支持的数字格式(NaN, infinities) 
  19.             throw new RuntimeException(e); 
  20.         } 
  21.  
  22.         return title; 
  23.     } 
/**
	 * 版本更新
	 * 
	 * @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;
	}

  1. /**
  2.      * 主页
  3.      *
  4.      * @param token
  5.      * @param firstopen
  6.      * @param mobiletype
  7.      * @param mobilesys
  8.      * @param vercode
  9.      * @return
  10.      */ 
  11.     public JSONObject getHomePageReques(int firstopen, 
  12.             String mobiletype, String mobilesys, String vercode) { 
  13.         JSONObject title = getContextJsonObj("HomePage"); 
  14.         try { 
  15.             // 另外一个Json对象需要新建 
  16.             JSONObject mQrInfo = new JSONObject(); 
  17.             mQrInfo.put("firstopen", firstopen); 
  18.             mQrInfo.put("mobiletype", mobiletype); 
  19.             mQrInfo.put("mobilesys", mobilesys); 
  20.             mQrInfo.put("vercode", vercode); 
  21.             // 将用户和码值添加到整个Json中 
  22.             title.put("data", mQrInfo); 
  23.  
  24.         } catch (JSONException e) { 
  25.             // 键为null或使用json不支持的数字格式(NaN, infinities) 
  26.             throw new RuntimeException(e); 
  27.         } 
  28.  
  29.         return title; 
  30.     } 
/**
	 * 主页
	 * 
	 * @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;
	}

  1. public String sendDataToServer(String url, String body) throws Exception { 
  2.  
  3.         HttpPost httpPost = new HttpPost(url); 
  4.         ByteArrayEntity postdata = new ByteArrayEntity(body.getBytes()); 
  5.         httpPost.setEntity(postdata); 
  6.         int res = 0; 
  7.  
  8.         HttpParams httpParameters = new BasicHttpParams(); 
  9.         HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT); 
  10.         HttpConnectionParams.setSoTimeout(httpParameters, TIME_OUT); 
  11.  
  12.         DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); 
  13.         HttpResponse httpResponse = httpClient.execute(httpPost); 
  14.         res = httpResponse.getStatusLine().getStatusCode(); 
  15.         if (res == 200) { 
  16.             String result = EntityUtils.toString(httpResponse.getEntity()); 
  17.             XLog.d("result==", result); 
  18.             return result; 
  19.  
  20.         } 
  21.  
  22.         return null; 
  23.     } 

转载于:https://my.oschina.net/pangzhuzhu/blog/318095

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值