import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; 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 android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; public class Update extends Activity { public ProgressDialog pBar; private Handler handler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.update); Dialog dialog = new AlertDialog.Builder(Update.this).setTitle("系统更新") .setMessage("发现新版本,请更新!")// 设置内容 .setPositiveButton("确定",// 设置确定按钮 new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { pBar = new ProgressDialog(Update.this); pBar.setTitle("正在下载"); pBar.setMessage("请稍候..."); pBar .setProgressStyle(ProgressDialog.STYLE_SPINNER); downFile("http://url:8765/OA.apk"); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // 点击"取消"按钮之后退出程序 } }).create();// 创建 // 显示对话框 dialog.show(); } void downFile(final String url) { pBar.show(); new Thread() { public void run() { HttpClient client = new DefaultHttpClient(); // params[0]代表连接的url 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(), "OA.apk"); fileOutputStream = new FileOutputStream(file); byte[] buf = new byte[1024]; int ch = -1; int count = 0; while ((ch = is.read(buf)) != -1) { // baos.write(buf, 0, ch); fileOutputStream.write(buf, 0, ch); count += ch; if (length > 0) { } } } fileOutputStream.flush(); if (fileOutputStream != null) { fileOutputStream.close(); } down(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.start(); } void down() { handler.post(new Runnable() { public void run() { pBar.cancel(); update(); } }); } void update() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File("/sdcard/OA.apk")), "application/vnd.android.package-archive"); startActivity(intent); } }

曾经用到过的一个Android工具类,版本检测、自动更新。通用性差,权当笔记。

package com.hiyo.game.pdk.tool; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.util.Log; import android.webkit.URLUtil; import com.hiyo.game.pdk.activity.R; /** * Android AutoUpdate. * * lazybone/2010.08.20 * * 1.Set apkUrl. * * 2.check(). * * 3.add delFile() method in resume()/onPause(). */ public class MyAutoUpdate { public Activity activity = null; public int versionCode = 0; public String versionName = ""; private static final String TAG = "AutoUpdate"; private String currentFilePath = ""; private String currentTempFilePath = ""; private String fileEx = ""; private String fileNa = ""; private String strURL = "http://127.0.0.1:81/ApiDemos.apk"; private ProgressDialog dialog; public MyAutoUpdate(Activity activity) { this.activity = activity; getCurrentVersion(); } public void check() { if (isNetworkAvailable(this.activity) == false) { return; } if (true) {// Check version. showUpdateDialog(); } } public static boolean isNetworkAvailable(Context ctx) { try { ConnectivityManager cm = (ConnectivityManager) ctx .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); return (info != null && info.isConnected()); } catch (Exception e) { e.printStackTrace(); return false; } } public void showUpdateDialog() { @SuppressWarnings("unused") AlertDialog alert = new AlertDialog.Builder(this.activity) .setTitle("Title") .setIcon(R.drawable.icon) .setMessage("Update or not?") .setPositiveButton("Update", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { downloadTheFile(strURL); showWaitDialog(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }).show(); } public void showWaitDialog() { dialog = new ProgressDialog(activity); dialog.setMessage("Waitting for update..."); dialog.setIndeterminate(true); dialog.setCancelable(true); dialog.show(); } public void getCurrentVersion() { try { PackageInfo info = activity.getPackageManager().getPackageInfo( activity.getPackageName(), 0); this.versionCode = info.versionCode; this.versionName = info.versionName; } catch (NameNotFoundException e) { e.printStackTrace(); } } private void downloadTheFile(final String strPath) { fileEx = strURL.substring(strURL.lastIndexOf(".") + 1, strURL.length()) .toLowerCase(); fileNa = strURL.substring(strURL.lastIndexOf("/") + 1, strURL.lastIndexOf(".")); try { if (strPath.equals(currentFilePath)) { doDownloadTheFile(strPath); } currentFilePath = strPath; Runnable r = new Runnable() { public void run() { try { doDownloadTheFile(strPath); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } } }; new Thread(r).start(); } catch (Exception e) { e.printStackTrace(); } } private void doDownloadTheFile(String strPath) throws Exception { Log.i(TAG, "getDataSource()"); if (!URLUtil.isNetworkUrl(strPath)) { Log.i(TAG, "getDataSource() It's a wrong URL!"); } else { URL myURL = new URL(strPath); URLConnection conn = myURL.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); if (is == null) { throw new RuntimeException("stream is null"); } File myTempFile = File.createTempFile(fileNa, "." + fileEx); currentTempFilePath = myTempFile.getAbsolutePath(); FileOutputStream fos = new FileOutputStream(myTempFile); byte buf[] = new byte[128]; do { int numread = is.read(buf); if (numread <= 0) { break; } fos.write(buf, 0, numread); } while (true); Log.i(TAG, "getDataSource() Download ok..."); dialog.cancel(); dialog.dismiss(); openFile(myTempFile); try { is.close(); } catch (Exception ex) { Log.e(TAG, "getDataSource() error: " + ex.getMessage(), ex); } } } private void openFile(File f) { Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(android.content.Intent.ACTION_VIEW); String type = getMIMEType(f); intent.setDataAndType(Uri.fromFile(f), type); activity.startActivity(intent); } public void delFile() { Log.i(TAG, "The TempFile(" + currentTempFilePath + ") was deleted."); File myFile = new File(currentTempFilePath); if (myFile.exists()) { myFile.delete(); } } private String getMIMEType(File f) { String type = ""; String fName = f.getName(); String end = fName .substring(fName.lastIndexOf(".") + 1, fName.length()) .toLowerCase(); if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) { type = "audio"; } else if (end.equals("3gp") || end.equals("mp4")) { type = "video"; } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg") || end.equals("bmp")) { type = "image"; } else if (end.equals("apk")) { type = "application/vnd.android.package-archive"; } else { type = "*"; } if (end.equals("apk")) { } else { type += "/*"; } return type; } }

//获取package名和版本: PackageManager manager = activity.getPackageManager(); PackageInfo info = manager.getPackageInfo(activity.getPackageName(), 0); packageName = info.packageName; versionName = info.versionName; //在这里获取服务端版本对比 //下载APK到本地 PACKAGE_SAVE_PATH //安装应用 Intent intent = new Intent(Intent.ACTION_VIEW); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(Uri.parse("file://" + PACKAGE_SAVE_PATH), "application/vnd.android.package-archive"); activity.startActivity(intent);

更多相关文章

  1. Android获取WiFi ip相关信息
  2. Android获取应用的签名信息
  3. android 返回键退出程序
  4. android 获取屏幕分辨率
  5. android朋友圈监听键盘状态 点击空白区域隐藏键盘
  6. android 获取当前系统的语言
  7. Android(安卓)Glide 升级4.8 后, 原方法error/preload/fallback
  8. 获取android正在运行的所有app进程
  9. Android腾讯微薄客户端开发十一:博主的粉丝

随机推荐

  1. 关于java.lang.NoSuchMethodException: [
  2. Android实现简单画图画板
  3. Android 调用intent 拍照
  4. Mac 真机调试android程序
  5. Android(安卓)Launcher全面剖析
  6. android 安装内核module,提示Required key
  7. flutter 打包 flutter build apk 报错Pro
  8. android 里的actionbar最右边的overflow
  9. Epub加密
  10. Android应用程序窗口View的measure过程