您的位置:首页 > 其它

Apk升级功能

2016-02-22 10:59 375 查看
总的思想:得到服务器上的版本号 ,与本地的apk的Manifest中版本号对比,若是服务器上的版本号比较大,则升级。

1.定义ApkInfo类来封装需要的信息。

public class ApkInfo {
	private String name;
	private String vercode;
	private String vername;
	private String apkaddr;
	public ApkInfo(String name, String vercode, String vername, String apkaddr) {
		super();
		this.name = name;
		this.vercode = vercode;
		this.vername = vername;
		this.apkaddr = apkaddr;
	}
	public ApkInfo() {
		super();
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getVercode() {
		return vercode;
	}
	public void setVercode(String vercode) {
		this.vercode = vercode;
	}
	public String getVername() {
		return vername;
	}
	public void setVername(String vername) {
		this.vername = vername;
	}
	public String getApkaddr() {
		return apkaddr;
	}
	public void setApkaddr(String apkaddr) {
		this.apkaddr = apkaddr;
	}

}


2.Manifest文件中的版本信息

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myfirstapp"
    android:versionCode="1"
    android:versionName="1.0" >


3.得到apk版本信息的工具类,其中封装从服务器中得到apk版本信息的方法。

public class UpdateTools {

	/**
	 * 获取相应网址的内容
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String getContent(String url) throws Exception {
		StringBuilder sb = new StringBuilder();
  
		HttpClient client = new DefaultHttpClient();
		HttpResponse response = client.execute(new HttpGet(url));
		HttpEntity entity = response.getEntity();
		if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
			return sb.toString();
		}
		if (entity != null) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					entity.getContent(), "UTF-8"), 8192);

			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			reader.close();
		} else {
		}
		return sb.toString();
	}

	public static final String UPDATE_VERJSON = "http://xxx/apks/config.html";

	public static ApkInfo getServerVerCode() {
		ApkInfo apkInfo=new ApkInfo();
		try {
			
			String verjson = getContent(UPDATE_VERJSON);
			JSONArray array = new JSONArray(verjson);
			if (array.length() > 0) {
				JSONObject obj = array.getJSONObject(0);
				try {
					apkInfo.setName(obj.getString("apkname"));
					apkInfo.setVername(obj.getString("verName")); 
					apkInfo.setVercode(obj.getString("verCode"));
					apkInfo.setApkaddr(obj.getString("verUrl")+"/"+obj.getString("apkname"));
					return apkInfo;
				} catch (Exception e) {
					e.printStackTrace();
					return apkInfo;
					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return apkInfo;
		}
		return apkInfo;
	}
	
}


4.对比本地apk的版本与服务器中apk的版本,若是服务器中版本大,则弹出对话框让用户选择是否升级

new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ApkInfo apkInfo = UpdateTools.getServerVerCode();
				if (apkInfo != null) {
					Message message = updatehandler.obtainMessage();
					message.obj = apkInfo;
					message.what = 1;
					updatehandler.sendMessage(message);
				}

			}
		}).start();


private Handler updatehandler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				ApkInfo apkInfo = (ApkInfo) msg.obj;
				if (apkInfo.getApkaddr() != null
						&& apkInfo.getVercode() != null
						&& apkInfo.getVername() != null) {
					int i = -1;
					try {
						i = Integer.parseInt(apkInfo.getVercode());
					} catch (Exception e) {
						// TODO: handle exception
					}
					if (i != -1 && i > getVerCode(getApplicationContext())) {
						if (mUpdatedialog != null && !mUpdatedialog.isShowing()) {
							mUpdatedialog
									.setMessage(getString(R.string.pengb_update_updatemessage1)
											+ " V"
											+ apkInfo.getVername()
											+ ","
											+ getString(R.string.pengb_update_updatemessage2));
							mUpdatedialog.show();
							mapkInfo = apkInfo;
						}
					}

				}
				break;
			case 4:
				if (mProgressDialog!=null&&mProgressDialog.isShowing()) {
					mProgressDialog.dismiss();	
				}
				Toast.makeText(getApplicationContext(), getString(R.string.pengb_update_downerror), 1000).show();
				break;
			case 3:
				mProgressDialog.setProgress(msg.arg1);
				break;
			default:
				break;
			}

		};
	};


public int getVerCode(Context context) {
		int i = 0;
		try {
			i = context.getPackageManager().getPackageInfo(
					"com.example.myfirstapp", 0).versionCode;
		} catch (NameNotFoundException e) {
			Log.e(TAG, e.getMessage());
		}
		return i;

	}
	public String getVerName(Context context) {
		try {
			return context.getPackageManager().getPackageInfo(
					"com.example.myfirstapp", 0).versionName;
		} catch (NameNotFoundException e) {
			Log.e(TAG, e.getMessage());
		}
		return null;

	}

其中,dialog为:

updateBuilder = new AlertDialog.Builder(this);
		updateBuilder.setTitle(getString(R.string.pengb_update_update));
		updateBuilder.setPositiveButton(getString(R.string.pengb_update_yes),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

						if (!mProgressDialog.isShowing()) {
							mProgressDialog.show();
						}
						if (mapkInfo!=null&&mapkInfo.getApkaddr()!=null) {
							downFile(mapkInfo.getApkaddr().toString());
						}
						
					}
				});
		updateBuilder.setNegativeButton(getString(R.string.pengb_update_no),
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						Settings.System.putInt(getContentResolver(), "mm_update_pb", 1);
						dialog.dismiss();
					}
				});
		updateBuilder.setCancelable(false);
		mUpdatedialog = updateBuilder.create();

		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setCancelable(false);
		mProgressDialog.setTitle(getString(R.string.pengb_update_downing));
		mProgressDialog
				.setMessage(getString(R.string.pengb_update_downingmessage));
		mProgressDialog.setButton(getString(R.string.pengb_update_cancel),
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						update=false;
						Settings.System.putInt(getContentResolver(), "mm_update_pb", 1);
						arg0.dismiss();
					}
				});
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);


5.在对话框中,选择不升级,则设置变量为1。选择升级,则开始下载服务器上的apk。

public void downFile(final String url) {
		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try {
					response = client.execute(get);
					if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
						Message message = handler.obtainMessage();
						message.what = 4;
						updatehandler.sendMessage(message);
						return ;
					}else {
						HttpEntity entity = response.getEntity();
						final int length = (int)(entity.getContentLength()/1024);
						updatehandler.post(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								mProgressDialog.setMax((int) length);
							}
						});
						InputStream is = entity.getContent();
						FileOutputStream fileOutputStream = null;
						if (is != null) {
							File file = new File("/var", "firstapp.apk");
							fileOutputStream = new FileOutputStream(file);
							byte[] buf = new byte[1024];
							int ch = -1;
							int count = 0;
							while ((ch = is.read(buf)) != -1) {
								fileOutputStream.write(buf, 0, ch);
								count += ch;
								Message message1 = updatehandler.obtainMessage();
								message1.what = 3;
								message1.arg1 = count/1024;
								updatehandler.sendMessage(message1);
							}
						}
						fileOutputStream.flush();
						if (fileOutputStream != null) {
							fileOutputStream.close();
						}
						is.close();
						updatehandler.post(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								if (mProgressDialog != null
										&& mProgressDialog.isShowing()) {
									mProgressDialog.dismiss();
								}
								int i=Settings.System.getInt(getContentResolver(), "mm_update_pb", 0);
								if (i==0) {
									update();
								}
								
							}
						});
					}
					
				} catch (ClientProtocolException e) {
					Message message = handler.obtainMessage();
					message.what = 4;
					updatehandler.sendMessage(message);
					e.printStackTrace();
				} catch (IOException e) {
					Message message = handler.obtainMessage();
					message.what = 4;
					updatehandler.sendMessage(message);
					e.printStackTrace();
				}
			}
		}.start();
	}


6.下载完后,进行升级

public void update() {
		try {
			String command = "chmod 777 " + "/var/firstapp.apk";
			Runtime runtime = Runtime.getRuntime();
			runtime.exec(command);
		} catch (IOException e) {
			Log.d(TAG, "chmod 666 fail!");
			e.printStackTrace();
		}
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(
				Uri.fromFile(new File("/var/sivitonlocalmm.apk")),
				"application/vnd.android.package-archive");
		startActivity(intent);
	}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: