Make an Android client for a website, and the user installs it on their phone. What if I make a new version? Have a version update feature.
The original version inspection is best done automatically. However, it would be a waste of time to check every time you start an application, since version updates are very rare. Maybe when the program is on, you can determine the time, one-day test, two-day test, or random or something, and reduce the frequency of testing?
The way I take is to do the detection function on the menu, the user needs to manually open their own detection. Anyway we this is the website client, version update, on the website to send a notice on the line.
There are several key steps for version detection and update:
1. Check whether there is a new version
2. Download the new version
3. Install and replace the new version
The solution I’m dealing with is
1, add a new file in assets folder: ver. CFG, record the version information, in plain text format, the content is only one sentence:
Version = 1.0Copy the code
This comes packaged with the installation on the user’s phone
Then inside the site, set up an XML file called ver_apk.xml, which also says this:
<string>1.0</string>
Copy the code
When testing, it will first visit the XML of the website, get the latest version number, and then compare it with the record in the ver.cfg file on the mobile phone. If there is a different version, it can be considered as a new version, prompting for update.
2, download is direct download, I still don’t know how to do breakpoint continuation
3, install replacement, the key is the signature. The signature of each version must be consistent. Otherwise, the new one cannot replace the old one, indicating that the installation is not complete.
— — — — — — — — — — — — — — — — — — — the weather is too cold, luo luo luo — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — –
This function is done in the menu, triggering code is as follows:
/ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
/ / the menu
/ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
private static final String urlApk = "http://3g.***.com/tool/***.apk";
private static final String urlVer = "http://3g.***.com/tool/ver_apk.xml";
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, Menu.FIRST + 1.5."Test update").setIcon(
android.R.drawable.ic_menu_upload);
menu.add(Menu.NONE,Menu.FIRST+2.4."Quit").setIcon(android.R.drawable.ic_lock_power_off);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case Menu.FIRST + 1:
Toast.makeText(this."Testing version", Toast.LENGTH_LONG).show();
UpdateVer uv = new UpdateVer(urlApk,urlVer,MainActivity.this);
uv.checkVer();
break;
case Menu.FIRST + 2:
confirmExit();
break;
}
return false;
}
Copy the code
Detection update because the code is more, written as a class to encapsulate
UpdateVer.java
package android.***;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.webkit.URLUtil;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;
import org.xml.sax.InputSource;
import java.text.SimpleDateFormat;
import java.util.Date;
public class UpdateVer extends Activity{
private static final String TAG = "DOWNLOADAPK";
private String PastVersion;
private String NowVersion;
public ProgressDialog pBar;
private String currentFilePath = "";
private String fileEx="";
private String fileNa="";
private String strURL="";
private String VersionUri ="";
private Context mContext;
private final String fileVer = "ver.cfg";
public UpdateVer(String urlapk,String urlver,final Context context){
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String ver = "? ver=" + df.format(new Date());// Mainly to avoid the phone's cache
strURL = urlapk + ver;
VersionUri = urlver + ver;
mContext = context;
}
public void checkVer(a) {
// Parse the Version page to obtain the Version number
getVersionxml(VersionUri);
}
private void compareVer(a) {
load();
// When the latest version is available
if(PastVersion ! =null && !PastVersion.equals(NowVersion)){
Dialog dialog = new AlertDialog.Builder(mContext).setTitle("System Update")
.setMessage(String.format("New version %s found, current version %s, please update!",NowVersion,PastVersion))// Set the content
// Set the ok button
.setPositiveButton("Sure"
,new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
pBar = new ProgressDialog(mContext);
pBar.setTitle("Downloading");
pBar.setMessage("One moment, please...");
pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
fileEx = strURL.substring(strURL.lastIndexOf(".") + 1,strURL.length()).toLowerCase();
fileEx = fileEx.substring(0,fileEx.lastIndexOf("?"));
fileNa = strURL.substring(strURL.lastIndexOf("/") + 1,strURL.lastIndexOf("."));
getFile(strURL);
}
}).setNegativeButton("Cancel".new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int whichButton) {
// Click the "Cancel" button to exit the program
}
}).create();/ / create
// Displays a dialog box
dialog.show();
}
else{
Toast.makeText(mContext, String.format("Current version %s",PastVersion), Toast.LENGTH_LONG).show(); }}private void getFile(final String strPath)
{
pBar.show();
try{
if (strPath.equals(currentFilePath) ){
getDataSource(strPath);
}
currentFilePath = strPath;
Runnable r = new Runnable(){
@Override
public void run(a)
{
try{
getDataSource(strPath);
}
catch(Exception e){ Log.e(TAG, e.getMessage(), e); }}};new Thread(r).start();
}
catch(Exception e){ e.printStackTrace(); }}/* Get the remote file */
private void getDataSource(String strPath) throws Exception {
if(! URLUtil.isNetworkUrl(strPath)) { Log.d("Tag"."error");
}
else {
/ * * / URL
URL myURL = new URL(strPath);
/* Set up a connection */
URLConnection conn = myURL.openConnection();
conn.connect();
/*InputStream download file */
InputStream is = conn.getInputStream();
if (is == null) {
Log.d("tag"."error");
throw new RuntimeException("File contents not read");
}
/* Create temporary file */
File myTempFile = File.createTempFile(fileNa, "." + fileEx);
myTempFile.getAbsolutePath();
/* Write files to temporary disk */
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);
/* Open the file to install */
openFile(myTempFile);
try {
is.close();
}
catch (Exception ex){
Log.d("Tag"."error");
Log.e(TAG, "error: "+ ex.getMessage(), ex); }}}/* Open a file on the phone */
private void openFile(File f) {
pBar.cancel();
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
/* call getMIMEType() to getMIMEType */
String type = getMIMEType(f);
/* Set the intent's file and MimeType */
intent.setDataAndType(Uri.fromFile(f),type);
mContext.startActivity(intent);
}
/* Determine the method of file MimeType */
private String getMIMEType(File f) {
String type = "";
String fName = f.getName();
/* Get the extension */
String end = fName.substring(fName.lastIndexOf(".") +1,fName.length()).toLowerCase();
/* Depending on the type of the extension, MimeType */
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")) {/* android.permission.INSTALL_PACKAGES */
type = "application/vnd.android.package-archive";
}
else{
type = "*";
}
/* If you can't open it directly, pop out the software list and give the user the option */
if(! end.equals("apk")){
type += "/ *";
}
return type;
}
private void getVersionxml(String resourceUrl){
GetVer gv = new GetVer();
gv.execute(resourceUrl);
}
private boolean load(a){
Properties properties = new Properties();
try{
InputStream stream = mContext.getAssets().open(fileVer);
//FileInputStream stream = mContext.openFileInput(fileVer);
// Read the contents of the file
properties.load(stream);
}
catch (FileNotFoundException e){
return false;
}
catch(IOException e){
return false;
}
catch(Exception e){
return false;
}
PastVersion = String.valueOf(properties.get("Version").toString());
return true;
}
/ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
// GetVer
/ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
class GetVer extends AsyncTask<String.Integer.String> {
@Override
protected String doInBackground(String... urlVer) {
String db = null;
URL url = null;
try {
url = new URL(urlVer[0]);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
InputSource is = null;
try {
is = new InputSource(url.openStream());
is.setEncoding("UTF-8");
db = SAXGetVersionService.readRssXml(is);
}
catch (Exception e) {
e.printStackTrace();
}
return db;
}
@Override
protected void onCancelled(a) {
super.onCancelled();
}
@Override
protected void onPostExecute(String result) { NowVersion = result; compareVer(); }}}Copy the code
\
Androidmanifest.xml to add a few words
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Copy the code
Reference article:
\
Download.csdn.net/detail/xtlv…
\
\
\
\
\
\