继承CordovaPlugin类实现Activity调用

package com.jiatianxia.version;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;


public class Version extends CordovaPlugin{
	// 作为回调传递参数
		CallbackContext callbackContext;
		String newVerName = "";// 新版本名称
		int newVerCode = -1;// 新版本号
		ProgressDialog pd = null;
		String UPDATE_SERVERAPK = "软件.apk";
		@Override
		public boolean execute(String action, JSONArray args,
				CallbackContext callbackContext) throws JSONException {
			this.callbackContext = callbackContext;
			if (action.equals("upVersion")) {
				updateVersion();
				callbackContext.success("调用成功");
			} else {
				return false;
			}

			callbackContext.success();
			return true;

		}
		
		// 判断是否更新版本
		public void updateVersion() {
			if (getServerVer()) {
				int verCode = this.getVerCode(cordova.getActivity());
				if (newVerCode > verCode) {
					doNewVersionUpdate();// 更新版本
				} else {
					notNewVersionUpdate();// 提示已是最新版本
				}
			}
		}

		/**
		 * 获得版本号
		 */
		public int getVerCode(Context context) {
			int verCode = -1;
			try {
				String packName = context.getPackageName();
				verCode = context.getPackageManager().getPackageInfo(packName, 0).versionCode;
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				Log.e("版本号获取异常", e.getMessage());
			}
			return verCode;
		}

		/**
		 * 获得版本名称
		 */
		public String getVerName(Context context) {
			String verName = "";
			try {
				String packName = context.getPackageName();
				verName = context.getPackageManager().getPackageInfo(packName, 0).versionName;
			} catch (NameNotFoundException e) {
				Log.e("版本名称获取异常", e.getMessage());
			}
			return verName;
		}

		/**
		 * 从服务器端获得版本号与版本名称
		 * 
		 * @return
		 */
		public boolean getServerVer() {
			try {
				URL url = new URL("服务器路径/version.text");
				HttpURLConnection httpConnection = (HttpURLConnection) url
						.openConnection();
				httpConnection.setDoInput(true);
				httpConnection.setDoOutput(true);
				httpConnection.setRequestMethod("GET");
				httpConnection.connect();
				InputStreamReader reader = new InputStreamReader(
						httpConnection.getInputStream());
				BufferedReader bReader = new BufferedReader(reader);
				String json = bReader.readLine();
				JSONArray array = new JSONArray(json);
				JSONObject jsonObj = array.getJSONObject(0);
				newVerCode = Integer.parseInt(jsonObj.getString("verCode"));
				newVerName = jsonObj.getString("verName");
			} catch (Exception e) {
				e.printStackTrace();
				return false;// 如果这里改为true 则不更新会退出程序
			}
			return true;
		}

		/**
		 * 不更新版本
		 */
		public void notNewVersionUpdate() {
			int verCode = this.getVerCode(cordova.getActivity());
			String verName = this.getVerName(cordova.getActivity());
			StringBuffer sb = new StringBuffer();
			sb.append("当前版本:");
			sb.append(verName);
			sb.append(" Code:");
			sb.append(verCode);
			sb.append("\n已是最新版本,无需更新");
			Dialog dialog = new AlertDialog.Builder(cordova.getActivity()).setTitle("软件更新")
					.setMessage(sb.toString())
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							// finish();
						}
					}).create();
			dialog.show();
		}

		/**
		 * 下载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;

							}
						}
						fileOutputStream.flush();
						if (fileOutputStream != null) {
							fileOutputStream.close();
						}
						down();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}.start();
		}

		/**
		 * 更新版本
		 */
		public void doNewVersionUpdate() {
			int verCode = this.getVerCode(cordova.getActivity());
			String verName = this.getVerName(cordova.getActivity());
			StringBuffer sb = new StringBuffer();
			sb.append("当前版本:");
			sb.append(verName);
			sb.append(" Code:");
			sb.append(verCode);
			sb.append(",发现版本:");
			sb.append(newVerName);
			sb.append(" Code:");
			sb.append(newVerCode);
			sb.append(",是否更新");
			Dialog dialog = new AlertDialog.Builder(cordova.getActivity())
					.setTitle("软件更新")
					.setMessage(sb.toString())
					.setPositiveButton("更新", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							pd = new ProgressDialog(cordova.getActivity());
							pd.setTitle("正在下载");
							pd.setMessage("请稍后");
							pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
							pd.setCancelable(false);
							new Thread() {
								double progress = 0;

								public void run() {
									try {
										while (progress < 94) {

											// 由线程来控制进度
											pd.setProgress((int) (progress += 0.18));
											Thread.sleep(100);
										}
										while (progress > 100) {
											pd.cancel();
										}
									} catch (Exception e) {
										pd.cancel();
									}
								}
							}.start();
							downFile("服务器路径/软件名.apk");
						}
					})
					.setNegativeButton("暂不更新",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									// finish();
								}
							}).create();
			// 显示更新框
			dialog.show();
		}

		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");
			cordova.getActivity().startActivity(intent);
		}

}
在上面的代码中我们通过Version extends CordovaPlugin类实现了不是Activity也可以进行对Activity的调用。关键方法
cordova.getActivity()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值