Android version detection Android program version detection and update implementation Introduction _android

Source: Internet
Author: User
Tags getmessage
Do a website of the Android client, the user installed to their mobile phone, if I have a new version how to do? To have a version update feature.
Original version detection is best done automatically. But if every time you open the program, you have to first detect a round, is a waste, after all, version update is a small probability of things. Perhaps the process can be opened, judge the time, a single day on the test, the date does not detect, or random what, to reduce the frequency of detection?

I took the approach is to do the detection function on the menu, users need to manually open their own test. Anyway we this is the website client, has the version to update, sends a notice on the website to be OK.
There are several key steps to version detection and update
1, detect any new version
2, download the new version
3, install replace new version
The solution I'm dealing with is
1, in the Assets folder to add a file: ver.cfg, record version information, plain text format, the content only a word:
Copy Code code as follows:

version=1.0


This will be packaged with the installation on the user's phone
Then in the site, set up an XML file Ver_apk.xml, the content is only this point:
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<string>1.0</string>

Detection, the first access to the Web site of the XML, get the latest version number, and then the phone with the Ver.cfg file recorded in the comparison, different words can be considered to have a new version, prompted to update.
2, download the words is directly downloaded, I do not know how to get the breakpoint continued transmission
3, installation and replacement, the key is the signature. is to keep the signatures of each version consistent. Otherwise the new cannot replace the old, prompting the installation to not complete.
-------------------The weather is too cold to giggle------------------------------------
This function is done on the menu, triggering the code as follows:
Copy Code code as follows:

//==========================================================================
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, "Detect Update"). SetIcon (
Android. R.drawable.ic_menu_upload);
Menu.add (menu.none,menu.first+2,4, "exit"). 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, "detecting version", Toast.length_long). Show ();
Updatever UV = new Updatever (urlapk,urlver,mainactivity.this);
Uv.checkver ();
Break
Case Menu.first + 2:
Confirmexit ();
Break
}
return false;
}

Detect updates because the code is more, write a class to encapsulate
Updatever.java
Copy Code code as follows:

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) {
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 () {
Parse version Web page, get build number
Getversionxml (Versionuri);
}
private void Comparever () {
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 ("found the new version%s, current version is%s, please update!") ", nowversion,pastversion))/set content
Set the OK button
. Setpositivebutton ("OK"
, new Dialoginterface.onclicklistener () {
@Override
public void OnClick (Dialoginterface dialog,
int which) {
Pbar = new ProgressDialog (mcontext);
Pbar.settitle ("Downloading");
Pbar.setmessage ("Please wait ...");
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 ();
Show dialog box
Dialog.show ();
}
else{
Toast.maketext (Mcontext, String.Format ("Currently the latest 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 ()
{
try{
Getdatasource (strpath);
}
catch (Exception e) {
LOG.E (TAG, E.getmessage (), E);
}
}
};
New Thread (R). Start ();
}
catch (Exception e) {
E.printstacktrace ();
}
}
/* Get remote File/* *
private void Getdatasource (String strpath) throws Exception {
if (! Urlutil.isnetworkurl (strpath)) {
LOG.D ("Tag", "error");
}
else {
/* Get url*/
URL myurl = new URL (strpath);
/* Set up online */
URLConnection conn = Myurl.openconnection ();
Conn.connect ();
/*inputstream Download File * *
InputStream is = Conn.getinputstream ();
if (is = = null) {
LOG.D ("tag", "Error");
throw new RuntimeException ("not read to file content");
}
* * Create TEMPORARY documents * *
File mytempfile = File.createtempfile (Filena, "." + Fileex);
Mytempfile.getabsolutepath ();
/* Write file to temp 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 File for installation * *
OpenFile (Mytempfile);
try {
Is.close ();
}
catch (Exception ex) {
LOG.D ("Tag", "error");
LOG.E (TAG, "error:" + ex.getmessage (), ex);
}
}
}
* * Open the 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 obtain mimetype * *
String type = GetMimeType (f);
/* Set Intent File and MimeType * *
Intent.setdataandtype (Uri.fromfile (f), type);
Mcontext.startactivity (Intent);
}
/* Judge the file MimeType method * *
Private String GetMimeType (File f) {
String type = "";
String fName = F.getname ();
/* Get extension * *
String end = fname.substring (Fname.lastindexof (".") +1,fname.length ()). toLowerCase ();

/* Determine mimetype by the type of extension * *
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 cannot open it directly, jump out of the list of software to select the user * *
if (!end.equals ("apk")) {
Type = = "/*";
}
return type;
}
private void Getversionxml (String resourceurl) {
Getver GV = new Getver ();
Gv.execute (ResourceUrl);
}
Private Boolean load () {
Properties Properties = new properties ();
try{
InputStream stream = Mcontext.getassets (). open (Filever);
FileInputStream stream = Mcontext.openfileinput (filever);
Read File contents
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 () {
Super.oncancelled ();
}
@Override
protected void OnPostExecute (String result) {
Nowversion = result;
Comparever ();
}
}
}

Androidmanifest.xml to add a few words
Copy Code code as follows:

<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 "/>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.