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!

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
