phonegap(cordova) 自定義插件代碼篇(二)----android 自動更新

程序總要更新的,apple 等appstore 處理,android版 自動更新,上代碼

/**
 * 檢查並更新APP 
 */

(function (cordova) {
    var define = cordova.define;

    define("cordova/plugin/updateApp", function (require, exports, module) {
        var argscheck = require('cordova/argscheck'),
	    exec = require('cordova/exec');
        exports.checkAndUpdate = function (content, successCB, failCB) {

            exec(successCB, failCB, "UpdateApp", "checkAndUpdate", content);

        };
        exports.getCurrentVersion = function (successCB, failCB) {
            exec(successCB, failCB, "UpdateApp", "getCurrentVersion", []);
        }
        exports.update = function (downUrl, successCB, failCB) {
            exec(successCB, failCB, "UpdateApp", "update", [downUrl]);
        }


    });
    cordova.addConstructor(function () {
        if (!window.plugins) {
            window.plugins = {};
        }
        console.log("將插件注入cordovaupdateApp...");
        window.plugins.updateApp = cordova.require("cordova/plugin/updateApp");
        console.log("updateApp注入結果:" + typeof (window.plugins.updateApp));

    });
})(cordova);

 
<feature name="UpdateApp">
		<param name="android-package" value="包名.UpdateAppPlugin" />
	</feature>

public class UpdateAppPlugin extends CordovaPlugin {

	/* 版本號檢查路徑 */
	private String checkPath;
	/* 新版本號 */
	private int newVerCode;
	/* 新版本名稱 */
	private String newVerName="yooshowNewVersion";
	/* APK 下載路徑 */
	private String downloadPath;
	/* 下載中 */
	private static final int DOWNLOAD = 1;
	/* 下載結束 */
	private static final int DOWNLOAD_FINISH = 2;
	/* 下載保存路徑 */
	private String mSavePath;
	/* 記錄進度條數量 */
	private int progress;
	/* 是否取消更新 */
	private boolean cancelUpdate = false;
	/* 上下文 */
	private Context mContext;
	/* 更新進度條 */
	private ProgressBar mProgress;
	private Dialog mDownloadDialog;

	private ProgressDialog pd = null;
	String UPDATE_SERVERAPK = "yooshowupdate.apk";

	@Override
	public boolean execute(String action, JSONArray args,
			CallbackContext callbackContext) throws JSONException {
		this.mContext = cordova.getActivity();
		if (action.equals("checkAndUpdate")) {
			Log.i("our", "檢查版本");
			this.checkPath = args.getString(0);
			checkAndUpdate();
		} else if (action.equals("getCurrentVersion")) {
			// 優化 縮短傳輸內容,減少流量
			// JSONObject obj = new JSONObject();
			// obj.put("versionCode", this.getCurrentVerCode());
			// obj.put("versionName", this.getCurrentVerName());
			callbackContext.success(this.getCurrentVerCode() + "");
		} else if (action.equals("getServerVersion")) {
			this.checkPath = args.getString(0);
			if (this.getServerVerInfo()) {
				// 優化 縮短傳輸內容,減少流量
				// JSONObject obj = new JSONObject();
				// obj.put("serverVersionCode", newVerCode);
				// obj.put("serverVersionName", newVerName);
				callbackContext.success(newVerCode + "");
			} else {
				callbackContext
						.error("can't connect to the server!please check [checkpath]");
			}

		} else if (action.equals("update")) {
			this.downloadPath = args.getString(0);
			showDownloadDialog();
		}
		return false;
	}

	/**
	 * 檢查更新
	 */
	private void checkAndUpdate() {
		if (getServerVerInfo()) {
			int currentVerCode = getCurrentVerCode();
			if (newVerCode > currentVerCode) {
				this.showNoticeDialog();
			}
		}
	}

	/**
	 * 獲取應用當前版本代碼
	 * 
	 * @param context
	 * @return
	 */
	private int getCurrentVerCode() {
		String packageName = this.mContext.getPackageName();
		int currentVer = -1;
		try {
			currentVer = this.mContext.getPackageManager().getPackageInfo(
					packageName, 0).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return currentVer;
	}

	/**
	 * 獲取應用當前版本名稱
	 * 
	 * @param context
	 * @return
	 */
	private String getCurrentVerName() {
		String packageName = this.mContext.getPackageName();
		String currentVerName = "";
		try {
			currentVerName = this.mContext.getPackageManager().getPackageInfo(
					packageName, 0).versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return currentVerName;
	}

	/**
	 * 獲取應用名稱
	 * 
	 * @param context
	 * @return
	 */
	private String getAppName() {
		return this.mContext.getResources().getText(R.string.app_name)
				.toString();
	}

	/**
	 * 獲取服務器上的版本信息
	 * 
	 * @param path
	 * @return
	 * @throws Exception
	 */
	private boolean getServerVerInfo() {
		try {
			StringBuilder verInfoStr = new StringBuilder();
			URL url = new URL(checkPath);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(5000);
			conn.connect();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "UTF-8"), 8192);
			String line = null;
			while ((line = reader.readLine()) != null) {
				verInfoStr.append(line + "\n");
			}
			reader.close();

			JSONArray array = new JSONArray(verInfoStr.toString());
			if (array.length() > 0) {
				JSONObject obj = array.getJSONObject(0);
				newVerCode = obj.getInt("verCode");
				newVerName = obj.getString("verName");
				downloadPath = obj.getString("apkPath");

				Log.i("our", newVerCode + newVerName + downloadPath);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;

	}

	/**
	 * 顯示軟件更新對話框
	 */
	private void showNoticeDialog() {
		// 構造對話框
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle("軟件更新");
		builder.setMessage("有新版本需要更新");
		// 更新
		builder.setPositiveButton("確定", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// dialog.dismiss();
				// 顯示下載對話框
				showDownloadDialog(); 
			}
		});
		// 稍後更新
		builder.setNegativeButton("取消", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		Dialog noticeDialog = builder.create();
		noticeDialog.show();
	}

	/**
	 * 顯示軟件下載對話框
	 */
	private void showDownloadDialog() {
		
		pd = new ProgressDialog(mContext);
		pd.setTitle("正在下載");
		pd.setMessage("請稍後...");
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		
		
		pd.setCancelable(false);//設置進度條是否可以按退回鍵取消
		//設置點擊進度對話框外的區域對話框不消失 
		pd.setCanceledOnTouchOutside(false);
		downloadApk();
	}

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

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			// 正在下載
			case DOWNLOAD:
				// 設置進度條位置
//				mProgress.setProgress(progress); 
				pd.setProgress(progress);
				break;
			case DOWNLOAD_FINISH:
				// 安裝文件
//				installApk();
				update();
				break;
			default:
				break;
			}
		};
	};

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

					File file = new File(mSavePath);
					// 判斷文件目錄是否存在
					if (!file.exists()) {
						file.mkdir();
					}
					File apkFile = new File(mSavePath, newVerName);
					FileOutputStream fos = new FileOutputStream(apkFile);
					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) {
							// 下載完成
							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();
			}
			// 取消下載對話框顯示
			mDownloadDialog.dismiss();
		}
	};

	/**
	 * 安裝APK文件
	 */
	private void installApk() {
		File apkfile = new File(mSavePath, newVerName);
		if (!apkfile.exists()) {
			return;
		}
		// 通過Intent安裝APK文件
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		mContext.startActivity(i);
	}

	/**
	 * 下載apk
	 */
	public void downFile(final String url) {
		pd.show();
		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					long length = entity.getContentLength();
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						File file = new File(
								Environment.getExternalStorageDirectory(),
								UPDATE_SERVERAPK);
						fileOutputStream = new FileOutputStream(file);
						byte[] b = new byte[1024];
						int charb = -1;
						int count = 0;
						while ((charb = is.read(b)) != -1) {
							fileOutputStream.write(b, 0, charb);
							count += charb;
							
							progress = (int) (((float) count / length) * 100);
							// 更新進度
							mHandler.sendEmptyMessage(DOWNLOAD);
							 
						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					down();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			pd.cancel();
			update();
		}
	};

	/**
	 * 下載完成,通過handler將下載對話框取消
	 */
	public void down() {
		new Thread() {
			public void run() {
				Message message = handler.obtainMessage();
				handler.sendMessage(message);
			}
		}.start();
	}

	/**
	 * 安裝應用
	 */
	public void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), UPDATE_SERVERAPK)),
				"application/vnd.android.package-archive");
		mContext.startActivity(intent);
	}
}
每次激活app都檢查更新
onResume: function () {
        setTimeout(function () {
            
            //檢查更新
            updateClient.check();

           

        }, 0);
        
    }
document.addEventListener("resume", yooshowApp.onResume, false);

var updateClient = {
    check: function (isAlert) {
        if (typeof (device) != "undefined" && device.platform == "Android") {
            if (localStorage.getItem("YooshowSession")) {
                //刪除提醒
                remind.delPersonRemind({ "ModuleID": "update" });
            }
            window.plugins.updateApp.getCurrentVersion(function (currentVersionCode) {
                yooshow.PostApp("CheckVersion", {}, function (result) {

                    //最新版本
                    var version = result.Version;
                    //是否強制更新
                    var force = result.Force;
                    //下載地址
                    var url = result.Url;
                    //描述
                    var description = result.Description;
                    if (parseInt(version) > parseInt(currentVersionCode)) {
                        //強制更新
                        if (force) {
                            window.plugins.updateApp.update(url, function () { }, function () { });
                        } else {
                            navigator.notification.confirm(description, function (button) {
                                if (button == 1) {
                                    window.plugins.updateApp.update(url, function () { }, function () { });
                                }
                            }, '發現新版本', '立即更新,稍後更新');
                        }
                    } else {
                        if (isAlert) {
                            yooshow.alert("您已是最新版本");
                        }
                    }

                });
            }, function () {

            });
        }

    }
}


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