版本更新

獲取本地app版本號


PackageManager pkgManager = context.getPackageManager();

PackageInfo info = pkgManager.getPackageInfo(context.getPackageName,0);

String  versionName = info.versionName;

int versionCode = info.versionCode;

eg: int versionCode = context.getPackageManager().getPackageInfo("com.bdyl.activity", 0).versionCode;


安裝apk

   Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(apkfile),"application/vnd.android.package-archive");


解析version.xml的工具類

<span style="font-size:18px;">package com.bdyl.upgrade;

import java.io.InputStream;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ParseXmlService {
	public HashMap<String, String> parseXml(InputStream inStream)
			throws Exception {
		HashMap<String, String> hashMap = new HashMap<String, String>();

		// 實例化一個文檔構建器工廠
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// 通過文檔構建器工廠獲取一個文檔構建器
		DocumentBuilder builder = factory.newDocumentBuilder();
		// 通過文檔通過文檔構建器構建一個文檔實例
		Document document = builder.parse(inStream);
		// 獲取XML文件根節點
		Element root = document.getDocumentElement();
		// 獲得所有子節點
		NodeList childNodes = root.getChildNodes();
		for (int j = 0; j < childNodes.getLength(); j++) {
			// 遍歷子節點
			Node childNode = (Node) childNodes.item(j);
			if (childNode.getNodeType() == Node.ELEMENT_NODE) {
				// Element childElement = (Element) childNode;
				// 版本號
				if ("version".equals(childNode.getNodeName())) {
					hashMap.put("version", childNode.getFirstChild()
							.getNodeValue());
				}
				// 軟件名稱
				else if (("name".equals(childNode.getNodeName()))) {
					hashMap.put("name", childNode.getFirstChild()
							.getNodeValue());
				}
				// 下載地址
				else if (("url".equals(childNode.getNodeName()))) {
					hashMap.put("url", childNode.getFirstChild().getNodeValue());
				}
			}
		}
		return hashMap;
	}
}
</span>


將解析出來的版本號跟本地app版本進行對比,判斷是否需要更新下載

<span style="font-size:18px;">package com.bdyl.upgrade;

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.util.HashMap;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
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 com.bdyl.activity.R;
import com.bdyl.constance.Logs;
import com.bdyl.utils.ToastUtils;

public class UpdateManager {
	
	private static final int DOWNLOAD = 1;//下載中 
	private static final int DOWNLOAD_FINISH = 2;//下載結束
	private static final int ISUPDATE = 3;//版本不一致
	HashMap<String, String> mHashMap;//保存解析的XML信息
	private String mSavePath;//下載保存路徑
	private int progress;//記錄進度條數量
	private boolean cancelUpdate = false;//是否取消更新

	private Context mContext;
	/* 更新進度條 */
	private Dialog mDownloadDialog;
	private ProgressBar mProgress;
	private TextView mShowProTxt;
	
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			// 正在下載
			case DOWNLOAD:
				mProgress.setProgress(progress);// 設置進度條位置
				mShowProTxt.setText(progress+"%");//顯示下載進度
				break;
			case DOWNLOAD_FINISH:
				installApk();// 安裝文件
				break;
			case ISUPDATE:// 版本不一致,彈出更新對話框
				showNoticeDialog();
				break;
			case 4:
				ToastUtils.show(
						mContext,
						mContext.getResources().getString(
								R.string.soft_update_no));
				break;
			}
		};
	};

	public UpdateManager(Context context) {
		this.mContext = context;
	}

	/**
	 * 檢測軟件更新
	 */
	public void checkUpdate() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				if (isUpdate()) {
					// 顯示提示對話框
					// showNoticeDialog();
					mHandler.sendEmptyMessage(3);
				} else {
					// ToastUtils.show(mContext,
					// mContext.getResources().getString(R.string.soft_update_no));
					// mHandler.sendEmptyMessage(4);
				}
			}
		}).start();

	}

	/**
	 * 檢查軟件是否有更新版本
	 * 
	 * @return
	 */
	private boolean isUpdate() {

		// 獲取當前軟件版本
		int versionCode = getVersionCode(mContext);

		// 從網絡獲取version.xml
		InputStream inStream = null;
		try {
			URL url = new URL("http://121.42.192.251:8080/apk/version.xml");
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.connect();
			inStream = con.getInputStream();
			ParseXmlService service = new ParseXmlService();
			mHashMap = service.parseXml(inStream);

		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (inStream != null) {
					inStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		// 本地模擬
		/*
		 * ParseXmlService service = new ParseXmlService(); InputStream inStream
		 * = ParseXmlService.class.getClassLoader()
		 * .getResourceAsStream("version.xml"); try { mHashMap =
		 * service.parseXml(inStream); } catch (Exception e) {
		 * e.printStackTrace(); } finally { try { if (inStream != null) {
		 * inStream.close(); } } catch (IOException e) { e.printStackTrace(); }
		 * }
		 */

		// 解析XML文件。 由於XML文件比較小,因此使用DOM方式進行解析

		if (null != mHashMap) {
			int serviceCode = Integer.valueOf(mHashMap.get("version"));
			// 版本判斷
			Logs.v("" + versionCode + "<serviceCode: " + serviceCode);
			if (serviceCode > versionCode) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 獲取軟件版本號
	 * 
	 * @param context
	 * @return
	 */
	private int getVersionCode(Context context) {
		int versionCode = 0;
		try {
			// 獲取軟件版本號,對應AndroidManifest.xml下android:versionCode
			versionCode = context.getPackageManager().getPackageInfo(
					"com.bdyl.activity", 0).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}

	/**
	 * 顯示軟件更新對話框
	 */
	private void showNoticeDialog() {
		// 構造對話框
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle(R.string.soft_update_title);
		builder.setMessage(R.string.soft_update_info);
		// 更新
		builder.setPositiveButton(R.string.soft_update_updatebtn,
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						// 顯示下載對話框
						showDownloadDialog();
					}
				});
		// 稍後更新
		builder.setNegativeButton(R.string.soft_update_later,
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		Dialog noticeDialog = builder.create();
		noticeDialog.show();
	}

	/**
	 * 顯示軟件下載對話框
	 */
	private void showDownloadDialog() {
		// 構造軟件下載對話框
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle(mContext.getResources().getString(
				R.string.soft_update_title));
		// 給下載對話框增加進度條
		LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.dialog_upgrade_layout, null);
		mProgress = (ProgressBar) v.findViewById(R.id.upgrade_progress);
		mShowProTxt = (TextView) v.findViewById(R.id.upgrade_showprogress_txt);
		builder.setView(v);
		// 取消更新
		builder.setNegativeButton(R.string.cancel, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				// 設置取消狀態
				cancelUpdate = true;
			}
		});
		mDownloadDialog = builder.create();
		mDownloadDialog.setCanceledOnTouchOutside(false);
		mDownloadDialog.show();
		// 現在文件
		downloadApk();

	}

	/**
	 * 下載apk文件
	 */
	private void downloadApk() {
		// 啓動新線程下載軟件
		new downloadApkThread().start();
	}

	/**
	 * 下載文件線程
	 * 
	 */
	private class downloadApkThread extends Thread {
		@Override
		public void run() {
			try {
				// 判斷SD卡是否存在,並且是否具有讀寫權限
				// 獲得存儲卡的路徑
				if (!Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					mSavePath = Environment.getDownloadCacheDirectory()
							.toString() + "/";
				} else {
					mSavePath = Environment.getExternalStorageDirectory()
							.toString() + "/";
				}
				URL url = new URL(mHashMap.get("url"));
				// 創建連接
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.connect();
				int length = conn.getContentLength();// 獲取文件大小
				// 創建輸入流
				InputStream is = conn.getInputStream();

				File apkFile = new File(mSavePath, mHashMap.get("name"));

				FileOutputStream fos = new FileOutputStream(apkFile, false);
				// FileOutputStream fos =
				// mContext.openFileOutput(mHashMap.get("name"),
				// mContext.MODE_WORLD_WRITEABLE);
				int count = 0;
				// 緩存
				byte buf[] = new byte[1024];
				// 寫入到文件中
				do {
					int numread = is.read(buf);
					count += numread;
					// 計算進度條位置
					progress = (int) (((float) count / length) * 100);
					// 更新進度
					mHandler.sendEmptyMessage(DOWNLOAD);
					if (numread <= 0) {
						Logs.v("over....");
						// 下載完成
						mHandler.sendEmptyMessage(DOWNLOAD_FINISH);

						break;
					}
					// 寫入文件
					fos.write(buf, 0, numread);
				} while (!cancelUpdate);// 點擊取消就停止下載.
				fos.close();
				is.close();
				// }
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {

			}

			// 取消下載對話框顯示
			mDownloadDialog.dismiss();
		}
	};

	/**
	 * 安裝APK文件
	 */
	private void installApk() {
		File apkfile = new File(mSavePath, mHashMap.get("name"));
		Logs.v("installApk." + apkfile.exists() + apkfile.getAbsolutePath());
		if (!apkfile.exists()) {
			return;
		}
		// 通過Intent安裝APK文件
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(apkfile),
				"application/vnd.android.package-archive");
		/*
		 * i.setDataAndType(Uri.parse(apkfile.getAbsolutePath()),
		 * "application/vnd.android.package-archive");
		 */
		mContext.startActivity(intent);
	}
}
</span>

xml

<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <ProgressBar
        android:id="@+id/upgrade_progress"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/x10"
        android:indeterminate="false"
        android:max="100" />

    <TextView
        android:id="@+id/upgrade_showprogress_txt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal" />

</LinearLayout></span>


     


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章