android自动更新升级APP

private void checkVersion( AppVersion appVersion){
		if(StringUtils.isEmpty(appVersion.getNum())){
			UIHelper.ToastMessage(Setting.this, "获取不到最新版本,请稍后重试");	
			return ;
		}
		if(Version.getName(Setting.this).compareTo(appVersion.getNum())>=0){
			UIHelper.ToastMessage(Setting.this, "当前版本号:"+appVersion.getNum()+"已是最新版本,谢谢使用");	
			return ;
		}
		checkUpdate(appVersion);
	}
	
	
	
	private void checkUpdate(final AppVersion appVersion){
		String info = "发现新版本的应用\n" +
				"本地版本" + Version.getName(Setting.this) + "\n" +
				"最新版本:" + appVersion.getNum() + "\n" +"是否立即更新";

			
			builder = new AlertDialog.Builder(this);
			builder.setTitle("程序自动更新")
				.setMessage(info)
				.setIcon(R.drawable.refresh)
				.setCancelable(false)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					  public void onClick(DialogInterface dialog, int id) {
						         doUpdate(appVersion.getApkAddress());
						        dialog.dismiss();
					}
				})
				.setNegativeButton("取消", new  DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int i) {
						 dialog.dismiss();
					}
				});
			
			apkhandler.post(new Runnable() {
				public void run() {
					Dialog dlg = builder.create();
					dlg.show();
				}
			});
	}
	
	private void doUpdate(final String apkDownAddr) {
		progressDlg = new ProgressDialog(this);
		progressDlg.setTitle("正在下载");
		progressDlg.setMessage("请稍候..");
		progressDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		handler.post(new Runnable() {
			public void run() {
				progressDlg.show();
			}
		});
		
		if (!isSdCardReady()) {
			UIHelper.ToastMessage(Setting.this, "SD卡没准备好");
			progressDlg.dismiss();
			return;
		}
		apkFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp/dianjiaqin_hy.apk";
		apkFile = new File(apkFilePath);
		if (apkFile.exists()) {
			apkFile.delete();
		}

		new Thread() {
			@Override
			public void run() {
				try{
				  HttpUtils.download(apkDownAddr, apkFilePath,new DefaultHttpClient(new BasicHttpParams()));
				 }catch(RuntimeException e){
					 UIHelper.ToastMessage(Setting.this, "更新失败,网络异常,请检查网络是否连接超时");
				 }
				apkhandler.post(new Runnable() {
					public void run() {
						progressDlg.cancel();
					}
				});
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
				Setting.this.startActivity(intent);
				applications.clearUserData();
				//applications.quit();
				AppManager.getAppManager().AppExit(getParent());
			}
		}.start();
	}
	
	public  boolean isSdCardReady() {
		return Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
	}

猜你喜欢

转载自913.iteye.com/blog/2039633