Androidリモート更新クライアント


これは工事から分離されたもので,外部から直接インタフェースを呼び出すことができる.
package unicall.unicom.uniwell;

import java.io.ByteArrayOutputStream;
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 org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;

public class UpdateManager {

	private Context mContext;

	//    
	private String updateMsg = "       ,    ?";
	private String version;
	//       URl  
	private String updateUrl = "http://222.137.116.11/unccp/do.php?order=9959&branch=shaolin_android_position";
	//       url
	private String apkUrl = "";
	private Dialog noticeDialog;

	private Dialog downloadDialog;
	/*         */
	private String savePath = "/sdcard/mobiletiketingupdate/";
	private String dataPath = File.separator + "data" + File.separator + "data"
			+ File.separator + "lab.shaolin.download" + File.separator + "apps"
			+ File.separator;
	String path = "";
	private String saveFileName = "";

	/*       ui   handler msg   */
	private ProgressBar mProgress;

	private static final int DOWN_UPDATE = 1;

	private static final int DOWN_OVER = 2;

	private int progress;

	private Thread downLoadThread;

	private boolean interceptFlag = false;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				mProgress.setProgress(progress);
				break;
			case DOWN_OVER:
				installApk();
				break;
			default:
				break;
			}
		};
	};

	public UpdateManager(Context context) {
		this.mContext = context;
		if (Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			path = savePath;
			saveFileName = savePath + "shaolin_android_position.apk";
		} else {
			path = dataPath;
			saveFileName = "shaolin_android_position.apk";
			//lhjtianji dataPath = savePath;
			//saveFileName = dataPath + "shaolin_android_position.apk";
		}
		// savePath=Environment.getExternalStorageDirectory()+"/mobiletiketingupdate/";
		// UpdateRelease.apk
	}
	
	

	//       Activity  
	public void checkUpdateInfo() {
		System.out
				.println("UPDATEmanager------------------------------93-------    -----");
		checkApk();
		if (!getAppVersionName().equals(version)) {
			//
			showNoticeDialog();
		}
	}

	public void checkApk() {
		// HttpGet    
		String strResult = "";
		HttpGet httpRequest = new HttpGet(updateUrl);
		//   HttpClient  
		HttpClient httpclient = new DefaultHttpClient();
		//   HttpClient,  HttpResponse
		HttpResponse httpResponse;
		try {
			httpResponse = httpclient.execute(httpRequest);
			//     
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				//         
				strResult = EntityUtils.toString(httpResponse.getEntity());
				ParserResult(strResult);
				// return strResult;
			} else {
				// return strResult;
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// return strResult;
	}

	private void showNoticeDialog() {
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle("      ");
		builder.setMessage(updateMsg);
		builder.setPositiveButton("  ", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				showDownloadDialog();
			}
		});
		builder.setNegativeButton("    ", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		noticeDialog = builder.create();
		noticeDialog.show();
	}

	private void showDownloadDialog() {
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle("      ");

		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.progress);
		builder.setView(v);
		builder.setNegativeButton("  ", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				interceptFlag = true;
			}
		});
		downloadDialog = builder.create();
		downloadDialog.show();

		downloadApk();
	}

	//        
	public static String exec(String[] args) {
		String result = "";
		ProcessBuilder processBuilder = new ProcessBuilder(args);
		Process process = null;
		InputStream errIs = null;
		InputStream inIs = null;
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int read = -1;
			process = processBuilder.start();
			errIs = process.getErrorStream();
			while ((read = errIs.read()) != -1) {
				baos.write(read);
			}
			baos.write('
'); inIs = process.getInputStream(); while ((read = inIs.read()) != -1) { baos.write(read); } byte[] data = baos.toByteArray(); result = new String(data); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (errIs != null) { errIs.close(); } if (inIs != null) { inIs.close(); } } catch (IOException e) { e.printStackTrace(); } if (process != null) { process.destroy(); } } return result; } private Runnable mdownApkRunnable = new Runnable() { @Override public void run() { try { System.out .println("UpdateManager--------------171--------- "); URL url = new URL(apkUrl); HttpURLConnection conn = (HttpURLConnection) url .openConnection(); conn.connect(); int length = conn.getContentLength(); InputStream is = conn.getInputStream(); if(!Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)){ System.out.println("246---------------no sd ka-----"); FileOutputStream outStream = mContext.openFileOutput(saveFileName , Context.MODE_WORLD_READABLE); int count = 0; if (is != null) { byte[] buf = new byte[1024]; do { int ch = 0; ch = is.read(buf); count += ch; progress = (int) (((float) count / length) * 100); // mHandler.sendEmptyMessage(DOWN_UPDATE); if (ch <= 0) { // System.out .println("UpdateManager---------------------199-------- ----"); mHandler.sendEmptyMessage(DOWN_OVER); break; } outStream.write(buf,0,ch); }while(!interceptFlag); } outStream.flush(); if (outStream != null) { outStream.close(); } if (is != null) { is.close(); } } else{ File file = new File(path); if (!file.exists()) { file.mkdir(); } String apkFile = saveFileName; File ApkFile = new File(apkFile); 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(DOWN_UPDATE); if (numread <= 0) { // System.out .println("UpdateManager---------------------199-------- ----"); mHandler.sendEmptyMessage(DOWN_OVER); break; } fos.write(buf, 0, numread); } while (!interceptFlag);// . fos.close(); is.close(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }; /** * apk * * @param url */ private void downloadApk() { downLoadThread = new Thread(mdownApkRunnable); downLoadThread.start(); } /** * apk * * @param url */ private void installApk() { File apkfile; if(!Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)){ System.out.println("updatemanager-------------335--------begin "); apkfile = new File("/data/data/unicall.unicom.uniwell/files/"+saveFileName); if (!apkfile.exists()) { return; } System.out .println("UpdateManaget-----------------------236-------- APK--------"); Intent i = new Intent(Intent.ACTION_VIEW); i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive"); mContext.startActivity(i); } else{ apkfile = new File(saveFileName); if (!apkfile.exists()) { return; } System.out .println("UpdateManaget-----------------------236-------- APK--------"); Intent i = new Intent(Intent.ACTION_VIEW); i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive"); mContext.startActivity(i); } } private String getAppVersionName() { String versionName = ""; try { // ---get the package info--- PackageManager pm = mContext.getPackageManager(); PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), 0); versionName = pi.versionName; System.out .println("UpdateManager-----------------------256------- ---" + versionName); if (versionName == null || versionName.length() <= 0) { return ""; } } catch (Exception e) { // Log.e( "Exception", e); } return versionName; } private void ParserResult(String str) { String[] array = str.split(","); version = array[0].trim(); apkUrl = array[1].trim(); Log.v("00000000000000000000", apkUrl); } }