Blame view

src/com/sqs/app/update/UpdateManager.java 10 KB
3c2353cd   杜方   1、畅游通核销app源码提交;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
  package com.sqs.app.update;
  
  import java.io.File;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.InputStream;
  import java.net.HttpURLConnection;
  import java.net.MalformedURLException;
  import java.net.URL;
  import java.text.DecimalFormat;
  
  import android.app.AlertDialog;
  import android.app.AlertDialog.Builder;
  import android.app.Dialog;
  import android.app.ProgressDialog;
  import android.content.Context;
  import android.content.DialogInterface;
  import android.content.DialogInterface.OnCancelListener;
  import android.content.DialogInterface.OnClickListener;
  import android.content.Intent;
  import android.content.pm.PackageInfo;
  import android.content.pm.PackageManager.NameNotFoundException;
  import android.net.Uri;
  import android.os.Environment;
  import android.os.Handler;
  import android.os.Message;
  import android.view.LayoutInflater;
  import android.view.View;
  import android.widget.ProgressBar;
  import android.widget.TextView;
  import android.widget.Toast;
  
  import com.ectrip.trips.check.R;
  
  /**
   * 应用程序更新工具包
   * @version 1.1
   * @created 2012-6-29
   */
  public class UpdateManager {
  
  	private static final int DOWN_NOSDCARD = 0;
  	private static final int DOWN_UPDATE = 1;
  	private static final int DOWN_OVER = 2;
  
  	private static final int DIALOG_TYPE_LATEST = 0;
  	private static final int DIALOG_TYPE_FAIL   = 1;
  
  	private static UpdateManager updateManager;
  
  	private Context mContext;
  	//通知对话框
  	private Dialog noticeDialog;
  	//下载对话框
  	private Dialog downloadDialog;
  	//'已经是最新' 或者 '无法获取最新版本' 的对话框
  	private Dialog latestOrFailDialog;
  	//进度条
  	private ProgressBar mProgress;
  	//显示下载数值
  	private TextView mProgressText;
  	//查询动画
  	private ProgressDialog mProDialog;
  	//进度值
  	private int progress;
  	//下载线程
  	private Thread downLoadThread;
  	//终止标记
  	private boolean interceptFlag;
  	//提示语
  	private String updateMsg = "";
  	//返回的安装包url
  	private String apkUrl = "";
  	//下载包保存路径
  	private String savePath = "";
  	//apk保存完整路径
  	private String apkFilePath = "";
  	//临时下载文件路径
  	private String tmpFilePath = "";
  	//下载文件大小
  	private String apkFileSize;
  	//已下载文件大小
  	private String tmpFileSize;
  
  	private String curVersionName = "";
  	private float curVersionCode;
  	private AppUpdateBean mUpdate;
  
  	private Handler mHandler = new Handler(){
  		public void handleMessage(Message msg) {
  			switch (msg.what) {
  				case DOWN_UPDATE:
  					mProgress.setProgress(progress);
  					mProgressText.setText(tmpFileSize + "/" + apkFileSize);
  					break;
  				case DOWN_OVER:
  					downloadDialog.dismiss();
  					installApk();
  					break;
  				case DOWN_NOSDCARD:
  					downloadDialog.dismiss();
  					Toast.makeText(mContext, "无法下载安装文件,请检查SD卡是否挂载", 3000).show();
  					break;
  			}
  		};
  	};
  
  	public static UpdateManager getUpdateManager() {
  		if(updateManager == null){
  			updateManager = new UpdateManager();
  		}
  		updateManager.interceptFlag = false;
  		return updateManager;
  	}
  
  	/**
  	 * 检查App更新
  	 * @param context
  	 * @param isShowMsg 是否显示提示消息
  	 */
  	public void checkAppUpdate(Context context, final boolean isShowMsg){
  		this.mContext = context;
  		getCurrentVersion();
  		if(isShowMsg){
  			if(mProDialog == null)
  				mProDialog = ProgressDialog.show(mContext, null, "正在检测,请稍后...", true, true);
  			else if(mProDialog.isShowing() || (latestOrFailDialog!=null && latestOrFailDialog.isShowing()))
  				return;
  		}
  		final Handler handler = new Handler(){
  			public void handleMessage(Message msg) {
  				//进度条对话框不显示 - 检测结果也不显示
  				if(mProDialog != null && !mProDialog.isShowing()){
  					return;
  				}
  				//关闭并释放释放进度条对话框
  				if(isShowMsg && mProDialog != null){
  					mProDialog.dismiss();
  					mProDialog = null;
  				}
  				if(msg.what==0){
  					showLatestOrFailDialog(DIALOG_TYPE_FAIL);
  				}else
  					//显示检测结果
  					if(msg.what == 1){
  						mUpdate = (AppUpdateBean)msg.obj;
  						if(mUpdate != null){
  							if(curVersionCode < Float.parseFloat(mUpdate.getVersion())){
  								apkUrl = mUpdate.getUrl();
  								updateMsg = mUpdate.getDesc();
  								showNoticeDialog();
  							}else if(isShowMsg){
  								showLatestOrFailDialog(DIALOG_TYPE_LATEST);
  							}
  						}
  					}else if(isShowMsg){
  						showLatestOrFailDialog(DIALOG_TYPE_FAIL);
  					}
  			}
  		};
  		new Thread(){
  			public void run() {
  				Message msg = new Message();
  				try {
  					msg.what = 0;
  				} catch (Exception e) {
  					msg.what = 0;
  					e.printStackTrace();
  				}
  				handler.sendMessage(msg);
  			}
  		}.start();
  	}
  
  	/**
  	 * 显示'已经是最新'或者'无法获取版本信息'对话框
  	 */
  	private void showLatestOrFailDialog(int dialogType) {
  		if (latestOrFailDialog != null) {
  			//关闭并释放之前的对话框
  			latestOrFailDialog.dismiss();
  			latestOrFailDialog = null;
  		}
  		AlertDialog.Builder builder = new Builder(mContext);
  		builder.setTitle("系统提示");
  		if (dialogType == DIALOG_TYPE_LATEST) {
  			builder.setMessage("您当前已经是最新版本");
  		} else if (dialogType == DIALOG_TYPE_FAIL) {
  			builder.setMessage("无法获取版本更新信息");
  		}
  		builder.setPositiveButton("确定", null);
  		latestOrFailDialog = builder.create();
  		latestOrFailDialog.show();
  	}
  
  	/**
  	 * 获取当前客户端版本信息
  	 */
  	private void getCurrentVersion(){
  		try {
  			PackageInfo info = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
  			curVersionName = info.versionName;
  			curVersionCode = info.versionCode;
  		} catch (NameNotFoundException e) {
  			e.printStackTrace(System.err);
  		}
  	}
  
  	/**
  	 * 显示版本更新通知对话框
  	 */
  	private void showNoticeDialog(){
  		AlertDialog.Builder builder = new Builder(mContext);
  		builder.setTitle("软件版本更新");
  		builder.setMessage(updateMsg);
  		builder.setPositiveButton("立即更新", new OnClickListener() {
  			@Override
  			public void onClick(DialogInterface dialog, int which) {
  				dialog.dismiss();
  				showDownloadDialog();
  			}
  		});
  		builder.setNegativeButton("以后再说", new OnClickListener() {
  			@Override
  			public void onClick(DialogInterface dialog, int which) {
  				dialog.dismiss();
  
  			}
  		});
  		noticeDialog = builder.create();
  		noticeDialog.show();
  	}
  
  	/**
  	 * 显示下载对话框
  	 */
  	private void showDownloadDialog(){
  		AlertDialog.Builder builder = new Builder(mContext);
  		builder.setTitle("正在下载新版本");
  
  		final LayoutInflater inflater = LayoutInflater.from(mContext);
  		View v = inflater.inflate(R.layout.app_update_progress, null);
  		mProgress = (ProgressBar)v.findViewById(R.id.update_progress);
  		mProgressText = (TextView) v.findViewById(R.id.update_progress_text);
  
  		builder.setView(v);
  		builder.setNegativeButton("取消", new OnClickListener() {
  			@Override
  			public void onClick(DialogInterface dialog, int which) {
  				dialog.dismiss();
  				interceptFlag = true;
  			}
  		});
  		builder.setOnCancelListener(new OnCancelListener() {
  			@Override
  			public void onCancel(DialogInterface dialog) {
  				dialog.dismiss();
  				interceptFlag = true;
  			}
  		});
  		downloadDialog = builder.create();
  		downloadDialog.setCanceledOnTouchOutside(false);
  		downloadDialog.show();
  
  		downloadApk();
  	}
  
  	private Runnable mdownApkRunnable = new Runnable() {
  		@Override
  		public void run() {
  			try {
  				String apkName = "OSChinaApp_"+mUpdate.getName()+".apk";
  				String tmpApk = "OSChinaApp_"+mUpdate.getName()+".tmp";
  				//判断是否挂载了SD卡
  				String storageState = Environment.getExternalStorageState();
  				if(storageState.equals(Environment.MEDIA_MOUNTED)){
  					savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/OSChina/Update/";
  					File file = new File(savePath);
  					if(!file.exists()){
  						file.mkdirs();
  					}
  					apkFilePath = savePath + apkName;
  					tmpFilePath = savePath + tmpApk;
  				}
  
  				//没有挂载SD卡,无法下载文件
  				if(apkFilePath == null || apkFilePath == ""){
  					mHandler.sendEmptyMessage(DOWN_NOSDCARD);
  					return;
  				}
  
  				File ApkFile = new File(apkFilePath);
  
  				//是否已下载更新文件
  				if(ApkFile.exists()){
  					downloadDialog.dismiss();
  					installApk();
  					return;
  				}
  
  				//输出临时下载文件
  				File tmpFile = new File(tmpFilePath);
  				FileOutputStream fos = new FileOutputStream(tmpFile);
  
  				URL url = new URL(apkUrl);
  				HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  				conn.connect();
  				int length = conn.getContentLength();
  				InputStream is = conn.getInputStream();
  
  				//显示文件大小格式:2个小数点显示
  				DecimalFormat df = new DecimalFormat("0.00");
  				//进度条下面显示的总文件大小
  				apkFileSize = df.format((float) length / 1024 / 1024) + "MB";
  
  				int count = 0;
  				byte buf[] = new byte[1024];
  
  				do{
  					int numread = is.read(buf);
  					count += numread;
  					//进度条下面显示的当前下载文件大小
  					tmpFileSize = df.format((float) count / 1024 / 1024) + "MB";
  					//当前进度值
  					progress =(int)(((float)count / length) * 100);
  					//更新进度
  					mHandler.sendEmptyMessage(DOWN_UPDATE);
  					if(numread <= 0){
  						//下载完成 - 将临时下载文件转成APK文件
  						if(tmpFile.renameTo(ApkFile)){
  							//通知安装
  							mHandler.sendEmptyMessage(DOWN_OVER);
  						}
  						break;
  					}
  					fos.write(buf,0,numread);
  				}while(!interceptFlag);//点击取消就停止下载
  
  				fos.close();
  				is.close();
  			} catch (MalformedURLException e) {
  				e.printStackTrace();
  			} catch(IOException e){
  				e.printStackTrace();
  			}
  
  		}
  	};
  
  	/**
  	 * 下载apk
  	 * @param url
  	 */
  	private void downloadApk(){
  		downLoadThread = new Thread(mdownApkRunnable);
  		downLoadThread.start();
  	}
  
  	/**
  	 * 安装apk
  	 * @param url
  	 */
  	private void installApk(){
  		File apkfile = new File(apkFilePath);
  		if (!apkfile.exists()) {
  			return;
  		}
  		Intent i = new Intent(Intent.ACTION_VIEW);
  		i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
  		mContext.startActivity(i);
  	}
  }