这是从工程里分离出来的,外界可以直接调用接口
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('\n'); 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); } }