Mandatory updates for Android applications are very useful. Especially for applications that have just been launched, there will definitely be more or less bugs, especially those involving mobile payment. If something goes wrong, it will cause relatively large losses, so mandatory Updates are particularly important.
Generally speaking, the strategy for forced updates is:
When the application starts, it requests the background, and the background sends the latest version of the application information (including the application Version number, name, update content description, server address for downloading the package, flag of whether to force update), etc.
Next we will write the implementation code based on the above ideas.
1.AndroidManifest configuration version information
The version identification of each Android apk is defined in AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.demo" android:versionCode="1" android:versionName="1.0.0"> <application> </application> </manifest>
Among them, package="com.demo" is our package name; android:versionCode="1" is the version code, which is an integer number; android:versionName="1.0.0 " is the version name, which is a string and is displayed to the user.
When you need to read the version number and version name in the AndroidManifest file, you can easily get it using packageManager. The code is as follows:
public static int getVerCode(Context context) { int verCode = -1; try { verCode = context.getPackageManager().getPackageInfo( "com.demo", 0).versionCode; } catch (NameNotFoundException e) { Log.e(TAG, e.getMessage()); } return verCode; } public static String getVerName(Context context) { String verName = ""; try { verName = context.getPackageManager().getPackageInfo( "com.demo", 0).versionName; } catch (NameNotFoundException e) { Log.e(TAG, e.getMessage()); } return verName; }
2. Perform version check
Place the latest version on the server apk file, such as: http://localhost/mydemo/demo.apk
At the same time, place the version information calling interface or file corresponding to this apk on the server, such as: http://localhost/mydemo/ ver.json
The content in ver.json is:
The code is as follows:
[{"appname":"jtapp12","apkname ":"jtapp-12-updateapksamples.apk","verName":1.0.1,"verCode":2}]
Then, read and check the version on the mobile client:
private boolean getServerVer () { try { String verjson = NetworkTool.getContent(Config.UPDATE_SERVER + Config.UPDATE_VERJSON); JSONArray array = new JSONArray(verjson); if (array.length() > 0) { JSONObject obj = array.getJSONObject(0); try { newVerCode = Integer.parseInt(obj.getString("verCode")); newVerName = obj.getString("verName"); } catch (Exception e) { newVerCode = -1; newVerName = ""; return false; } } } catch (Exception e) { Log.e(TAG, e.getMessage()); return false; } return true; }
Compare the server and client versions and perform update operations.
if (getServerVerCode()) { int vercode = Config.getVerCode(this); // 用到前面第一节写的方法 if (newVerCode > vercode) { doNewVersionUpdate(); // 更新新版本 } else { notNewVersionShow(); // 提示当前为最新版本 } }
Calling method:
private void notNewVersionShow() { int verCode = Config.getVerCode(this); String verName = Config.getVerName(this); StringBuffer sb = new StringBuffer(); sb.append("当前版本:"); sb.append(verName); sb.append(" Code:"); sb.append(verCode); sb.append(",\n已是最新版,无需更新!"); Dialog dialog = new AlertDialog.Builder(Update.this).setTitle("软件更新") .setMessage(sb.toString())// 设置内容 .setPositiveButton("确定",// 设置确定按钮 new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }).create();// 创建 // 显示对话框 dialog.show(); } private void doNewVersionUpdate() { int verCode = Config.getVerCode(this); String verName = Config.getVerName(this); StringBuffer sb = new StringBuffer(); sb.append("当前版本:"); sb.append(verName); sb.append(" Code:"); sb.append(verCode); sb.append(", 发现新版本:"); sb.append(newVerName); sb.append(" Code:"); sb.append(newVerCode); sb.append(", 是否更新?"); Dialog dialog = new AlertDialog.Builder(Update.this) .setTitle("软件更新") .setMessage(sb.toString()) // 设置内容 .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(Config.UPDATE_SERVER + Config.UPDATE_APKNAME); } }) .setNegativeButton("暂不更新", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // 点击"取消"按钮之后退出程序 finish(); } }).create();// 创建 // 显示对话框 dialog.show(); }
Update download:
void downFile(final String url) { pBar.show(); new Thread() { public void run() { HttpClient client = new DefaultHttpClient(); 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(), Config.UPDATE_SAVENAME); 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; if (length > 0) { } } } fileOutputStream.flush(); if (fileOutputStream != null) { fileOutputStream.close(); } down(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }.start(); }
The download is completed, and the main ui thread is notified through the handler to cancel the download dialog box.
void down() { handler.post(new Runnable() { public void run() { pBar.cancel(); update(); } }); }
Install the application
void update() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(Environment .getExternalStorageDirectory(), Config.UPDATE_SAVENAME)), "application/vnd.android.package-archive"); startActivity(intent); }
If you publish the apk application to the market, Then, you will find that the market has a similar module built in, which can automatically update or remind you whether to update the application. So, if your own application needs to be automatically updated, wouldn't it be more convenient to build one yourself? Most of the code mentioned in this article is implemented in UpdateActivity.Java. In order to make the update process more friendly, you can create a thread in the initial launcher's Activity to check whether there are updates on the server. Start UpdateActivity when there is an update, which makes the user experience smoother.
The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.
For more Android application forced update APP related articles, please pay attention to the PHP Chinese website!