Android 版本检测和更新的主要方法
现在很多APK都自带自动检测版本及更新,以便用户体验到最新的功能和体验。实现方法分2种情况。
1.Google APP Store上面已经有部署,这种比较简单,在自己的服务器添加一个检查版本更新的页面,返回需要的版本信息,也可以添加描述内容,这样可以在APK显示版本更新的具体内容。新开一个线程检测当前的版本号是否小于最新的version,如果是的话,则开始访问官方地址来更新。代码如下:
/* This Thread checks for Updates in the Background */ private Thread checkUpdate = new Thread() { public void run() { try { URL updateURL = new URL("http://my.company.com/update"); URLConnection conn = updateURL.openConnection(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while((current = bis.read()) != -1){ baf.append((byte)current); } /* Convert the Bytes read to a String. */ final String s = new String(baf.toByteArray()); /* Get current Version Number */ int curVersion = getPackageManager().getPackageInfo("your.app.id", 0).versionCode; int newVersion = Integer.valueOf(s); /* Is a higher version than the current already out? */ if (newVersion > curVersion) { /* Post a Handler for the UI to pick up and open the Dialog */ mHandler.post(showUpdate); } } catch (Exception e) { } } }; /* This Runnable creates a Dialog and asks the user to open the Market */ private Runnable showUpdate = new Runnable(){ public void run(){ new AlertDialog.Builder(Test.this) .setIcon(R.drawable.icon) .setTitle("Update Available") .setMessage("An update for is available!\\n\\nOpen Android Market and see the details?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked OK so do some stuff */ Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:your.app.id")); startActivity(intent); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked Cancel */ } }) .show(); } }; }
2.产品没有部署在应用商店,可以在返回数据里添加最新版本APK的下载路径,下载完毕后,执行下列代码进行安装:
protected void installApk(File file) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); startActivity(intent); }
3.一些类库,参考地址: