Android版本更新及提示安装

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.http.AndroidHttpClient;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.widget.Toast;

public class SplashActivity extends Activity {

	public static final String TAG = "SplashActivity";

	public static final int WHAT_SHOW_UDPATE = 0;
	public static final int WHAT_DOWNLOAD_ERROR = 1;
	private static final int WHAT_NET_ERROR = 2;// 联网失败的错误信息

	private static final int REQUEST_INSTALL_CODE = 100;// 请求安装应用程序的标记

	private TextView mTvVersion;

	private String mVersionDesc;// 版本的描述信息
	private String mUrl;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			// 在主线程中执行

			switch (msg.what) {
			case WHAT_SHOW_UDPATE:
				showUpdateDialog();
				break;
			case WHAT_DOWNLOAD_ERROR:
				Toast.makeText(getApplicationContext(), "下载失败",
						Toast.LENGTH_SHORT).show();
				break;
			case WHAT_NET_ERROR:
				Toast.makeText(getApplicationContext(), msg.obj.toString(),
						Toast.LENGTH_SHORT).show();

				// 跳转到主页
				load2Main();
				break;
			default:
				break;
			}

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);

		// 初始化view
		initView();

		// 初始化数据
		initData();
	}

	private void initView() {
		mTvVersion = (TextView) findViewById(R.id.splash_tv_version);
	}

	private void initData() {
		// 给textView设置版本号
		// 获得版本号
		mTvVersion.setText("版本号:" + PackageInfoUtils.getVersionName(this));

		// 检测更新
		if (PreferenceUtils.getBoolean(this, Constants.AUTO_UPDATE, true)) {
			new Thread(new CheckVersionTask()).start();
		} else {
			load2Main();
		}
	}	
	/**
	 * 进入主页
	 */
	private void load2Main() {
		// 延时执行
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				// 是在主线程中执行的
				Logger.d(TAG, "" + Thread.currentThread().getName());

				Intent intent = new Intent(SplashActivity.this,
						HomeActivity.class);
				startActivity(intent);

				finish();
			}
		}, 1500);
	}

	private class CheckVersionTask implements Runnable {

		@Override
		public void run() {
			// 去服务器获得最新的版本号
			// 服务器:提供最新的版本信息

			AndroidHttpClient client = AndroidHttpClient.newInstance("bsj");

			// 设置超时时间
			HttpConnectionParams.setConnectionTimeout(client.getParams(),
					5 * 1000);// 设置请求超时的时长
			HttpConnectionParams.setSoTimeout(client.getParams(), 5 * 1000);// 设置响应的超时时长

			String uri = "http://188.188.6.100:8080/update.json";
			HttpGet get = new HttpGet(uri);
			// 执行
			try {
				HttpResponse response = client.execute(get);

				// 获得返回的结果码
				int statusCode = response.getStatusLine().getStatusCode();
				if (200 == statusCode) {
					// 获得成功
					String json = EntityUtils.toString(response.getEntity(),
							"utf-8");

					Logger.d(TAG, "json : " + json);

					// {"versionCode":2,"versionDesc":"描述","url":"http://188.188.6.100:8080/mobilesafe.apk"}
					// 解析json
					JSONObject jsonObject = new JSONObject(json);
					int netVersion = jsonObject.getInt("versionCode");
					// 获得本地的版本号
					int localVersion = PackageInfoUtils
							.getVersionCode(SplashActivity.this);

					if (netVersion > localVersion) {
						mVersionDesc = jsonObject.getString("versionDesc");
						mUrl = jsonObject.getString("url");

						// 需要更新
						Message msg = mHandler.obtainMessage();
						msg.what = WHAT_SHOW_UDPATE;// 显示更新的dialog
						msg.sendToTarget();
					} else {
						// 不需要更新
						load2Main();
					}
				} else {
					// 获得失败
					Message msg = mHandler.obtainMessage();
					msg.what = WHAT_NET_ERROR;// 显示更新的dialog
					msg.obj = "Error:1000";
					msg.sendToTarget();
				}
			} catch (ClientProtocolException e) {
				// e.printStackTrace();

				Message msg = mHandler.obtainMessage();
				msg.what = WHAT_NET_ERROR;// 显示更新的dialog
				msg.obj = "Error:1001";
				msg.sendToTarget();

			} catch (IOException e) {
				// e.printStackTrace();

				Message msg = mHandler.obtainMessage();
				msg.what = WHAT_NET_ERROR;// 显示更新的dialog
				msg.obj = "Error:1002";
				msg.sendToTarget();

			} catch (JSONException e) {
				// e.printStackTrace();

				Message msg = mHandler.obtainMessage();
				msg.what = WHAT_NET_ERROR;// 显示更新的dialog
				msg.obj = "Error:1003";
				msg.sendToTarget();
			}

			// 关闭连接
			client.close();
		}
	}

	private void showUpdateDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setCancelable(false);// 设置dialog不可以取消
		// 设置title
		builder.setTitle("版本更新提醒");
		// 设置内容部分
		builder.setMessage(mVersionDesc);
		// 设置点击按钮
		builder.setPositiveButton("立即更新", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// 去下载更新
				// 根据服务器提供的url,去下载最新的版本
				downloadNewApk();
			}
		});
		builder.setNegativeButton("稍后再说", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				load2Main();
			}
		});

		builder.show();
	}

	protected void downloadNewApk() {
		// 显示下载的进度条
		ProgressDialog dialog = new ProgressDialog(this);
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setCancelable(false);// 设置不可取消
		dialog.show();

		// 下载apk
		new Thread(new DownloadTask(dialog)).start();
	}

	private class DownloadTask implements Runnable {
		private ProgressDialog mDialog;

		public DownloadTask(ProgressDialog dialog) {
			this.mDialog = dialog;
		}

		@Override
		public void run() {
			AndroidHttpClient client = AndroidHttpClient.newInstance("bsj");

			// url
			HttpGet get = new HttpGet(mUrl);

			InputStream is = null;
			FileOutputStream fos = null;
			try {
				HttpResponse response = client.execute(get);
				int statusCode = response.getStatusLine().getStatusCode();
				if (200 == statusCode) {
					// 读取流信息
					is = response.getEntity().getContent();
					// 将流写成文件

					File file = new File(
							Environment.getExternalStorageDirectory(),
							System.currentTimeMillis() + ".apk");

					// 输出流
					fos = new FileOutputStream(file);

					long contentLength = response.getEntity()
							.getContentLength();
					Logger.d(TAG, "total : " + contentLength);
					mDialog.setMax((int) contentLength);

					byte[] buffer = new byte[1024];
					int len = -1;
					int progress = 0;
					while ((len = is.read(buffer)) != -1) {
						fos.write(buffer, 0, len);

						Thread.sleep(20);

						progress += len;
						// 写进度
						Logger.d(TAG, "progress : " + progress);
						mDialog.setProgress(progress);
					}

					// dialog消失
					mDialog.dismiss();

					// 提示用户安装
					showInstall(file);
				} else {
					// 主线程中执行
					Message msg = mHandler.obtainMessage();
					msg.what = WHAT_DOWNLOAD_ERROR;
					msg.sendToTarget();

					// 跳转到主页
					load2Main();
				}
			} catch (ClientProtocolException e) {
				// e.printStackTrace();
				Message msg = mHandler.obtainMessage();
				msg.what = WHAT_NET_ERROR;// 显示更新的dialog
				msg.obj = "Error:1004";
				msg.sendToTarget();

			} catch (IOException e) {
				// e.printStackTrace();

				Message msg = mHandler.obtainMessage();
				msg.what = WHAT_NET_ERROR;// 显示更新的dialog
				msg.obj = "Error:1005";
				msg.sendToTarget();
			} catch (InterruptedException e) {
				// e.printStackTrace();

				Message msg = mHandler.obtainMessage();
				msg.what = WHAT_NET_ERROR;// 显示更新的dialog
				msg.obj = "Error:1006";
				msg.sendToTarget();
			} finally {
				closeIO(is);
				closeIO(fos);
			}

			// 关闭连接
			client.close();
		}
	}

	private void closeIO(Closeable io) {
		if (io != null) {
			try {
				io.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			io = null;
		}
	}
	private void showInstall(File file) {
		// TODO:
		// 
		// 
		// 
		// 
		// 
		// 
		// 

		Intent intent = new Intent();
		intent.setAction("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");

		// startActivity(intent);
		startActivityForResult(intent, REQUEST_INSTALL_CODE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		// requestCode:请求的code,start时指定
		// resultCode: 是有开启后的activity提供的, setResult()
		if (requestCode == REQUEST_INSTALL_CODE) {
			// 开启安装请求的回调

			// android系统,将用户行为分为两种:确定,取消
			switch (resultCode) {
			case Activity.RESULT_OK:
				// 确定
				break;
			case Activity.RESULT_CANCELED:
				// 取消
				load2Main();
				break;
			default:
				break;
			}

		}

	}
}

你可能感兴趣的:(Android基础总结)