Android App Check Update summary

Source: Internet
Author: User

Each application should have an interface between the main interface to display the company or team information, introduce the software, and check the update, timely remind users to update the latest version, to get more and better user experience. This article will summarize the implementation, in the future, do not look for their own writing projects.

It is customary for us to define the class that implements this function as splashactivity.

Entering the interface should initialize some data, such as copying files to the system directory, copying the packaged database to the system directory, checking whether the software version is updated, and so on.

1, Copying files to the system directory has been written as a tool class, so as long as the source and destination address of the file to complete the replication. The following is the file directory code for obtaining the SD card under the Android platform as follows:


/** * Get file path and status information *  * @return */private list<myfileinfo> getFiles () {file path = null; list<myfileinfo> infos = new arraylist<myfileinfo> (); Myfileinfo info = null;//Determines if the SD card is available if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) { Path = Environment.getexternalstoragedirectory (); file[] files = path.listfiles (); for (File file:files) {//Put the path into the collection if (file.getpath () = null) {info = new myfileinfo (); Nfo.setpath (File.getpath ()); Infos.add (info); info = null;}}} else {toast.maketext (filesearchactivity.this, "SD card not available!"). Show (); return infos;}
Copy file Method:

/** * @warning The name of the file must is end with. xls * @param res the resource file * @param des the destination * @retur N  * @throws filenotfoundexception  */public Static Boolean tocopy (String res,string des) {Boolean flag=false;// Input source files File File = new file (res); FileInputStream fr=null;//Copy destination file Desfile = new file (DES); FileOutputStream Bw=null;try {fr = new FileInputStream (file), bw = new FileOutputStream (desfile);//bufferbyte[] B = new Byt E[512];while (Fr.read (b)!=-1) {bw.write (b);} Bw.flush (); flag=true;} catch (FileNotFoundException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Finally{if (fr! = null) try {fr.close ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} if (BW = null) {try {bw.close ()} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} return flag;}

To get the Android app system catalog:

File File = new file (Getfilesdir (), "Xxx.xls"), in Android data/data/the package name/files directory.
You can use the above method to copy the SD card files to the application system directory.
2. Copy the database to the system directory
<p> (1) Get System files directory: </p><p><span style= "Color:rgb (127, 0, 85);" >final</span> file file = <span style= "Color:rgb (127, 0, 85); >new</span> file (Getfilesdir (),  <span style= "Color:rgb (42, 0, 255);" > "xxx.db" </span>);</p><p> (2) get the input stream of the file located in the Asset directory </p><p>inputstream is =  getassets (). Open (<span style= "Color:rgb (42, 0, 255);" > "xxx.db" </span>); </p><p>getresources () </p><p>*<span style= "font-family: the song Body;" > Read File resources: </span><span style= "Font-family:times New Roman;" >1.</span><span style= "font-family: the song Body;" > Read </span><span style= "Font-family:times New Roman;" >res/raw</span><span style= "font-family: the song Body;" > File resources, get the input stream for write operations in the following ways </span>         <span style= " Font-family:times New Roman; " >inputstream is =getresources (). Openrawresource (r.id.filename); &nbSp;</span>2.<span style= "font-family: the song Body;" > Read </span><span style= "Font-family:times New Roman;" >assets</span><span style= "font-family: the song Body;" > File resources, get the input stream for write operations in the following ways </span>         <span style= " Font-family:times New Roman; " >AssetManager am = null; </span>·         <span style= "Font-family:times New Roman;" >am = getassets ();  </span>         <span style= "Font-family:times New Roman;" >inputstream is = am.open ("filename"); </span></p><p> </p> <p> </p><p>2<span style= "font-family: the song Body;" >, read the Copy to the system database, and obtain the database reference. Then you can manipulate the database. </span></p><p>sqlitedatabase db = sqlitedatabase.opendatabase (<span style= " Color:rgb (0,0,192); " >path</span>, <span style= "Color:rGB (127,0,85); " >null</span>,</p><p>sqlitedatabase.<span style= "Color:rgb (0,0,192);" >OPEN_READONLY</span>); </p><p> </p><p><span style= "Background:rgb ( 255,255,0); " > Note: The path to the database file copied to the system is: </span><span style= "Color:rgb (127, 0, 85); >public</span> <span style= "Color:rgb (127, 0, 85); >static</span> <span style= "Color:rgb (127, 0, 85); >final</span> string <span style= "Color:rgb (0, 0, 192); >path</span> = <span style= "Color:rgb (42, 0, 255); > "/data/data/</span><span style=" Color:rgb (42, 0, 255); " > Application Package name </span><span style= "Color:rgb (42, 0, 255); >/files/</span><span style= "Color:rgb (42, 0, 255); > Database files </span><span style= "Color:rgb (42, 0, 255); > "</span>;</p><p> self-established database is Databases<span style=" font-family: Song body; > folder. </span></p><p> </p>
The tool classes are as follows:
<pre name= "code" class= "Java" >public class Copyfiletosystem {public Copyfiletosystem () {//TODO auto-generated Constructor stub}/** * Copy files to system Folder * @param in * @param destpath */public static void CopyFile (InputStream in,string DESTP ATH) {//target file File=new files (destpath); FileOutputStream fos=null;try {fos=new fileoutputstream (file); int len=0;byte[] Buffer=new byte[1024];while ((len= In.read (buffer))!=-1) {fos.write (Buffer,0,len);} Fos.flush (); Fos.close (); In.close ();} catch (Exception e) {}}}


3. Check for Updates
(1) Get the app version number first
<pre name= "code" class= "java" >/** * Get App version info * @return App version number */private String getappversion () {Packagemanager pm=g Etpackagemanager (); PackageInfo info=null;try {info=pm.getpackageinfo (getpackagename (), 0); if (info!=null) {return info.versionname;}} catch (Namenotfoundexception e) {e.printstacktrace ();} Return "";}

(2) The configuration file that connects to the network resolution server at the same time gets the latest version number of the app, as follows:
<span style= "White-space:pre" ></span>1) server-side XML file as follows
<?xml version= "1.0" encoding= "Utf-8"?><info><version>2.0</version><description> Airborne new version, please download, experience more new features!!! </description><apkurl>http://192.168.253.1:8080/TouristManager.apk</apkurl></info>
<span style= "White-space:pre" ></span>2) connection server get input stream parsing xml file
<span style= "White-space:pre" ></span><pre name= "code" class= "Java" >public class Updateinfoparser { /** * The update information returned by the parsing server * @param the stream returned by the IS server * @return returns NULL if an exception occurs; */public static UpdateInfo Getupdateinfo (InputStream is) {try {xmlpullparser parser = Xml.newpullparser (); Parser.setinput (IS, "utf-8"); int type = Parser.geteventtype (); UpdateInfo info = null;while (type!=xmlpullparser.end_document) {switch (type) {case XmlPullParser.START_TAG:if ("info" . Equals (Parser.getname ())) {info = new UpdateInfo ();} else if ("Version". Equals (Parser.getname ())) {info.setversion (Parser.nexttext ());} else if ("description". Equals (Parser.getname ())) {info.setdescription (Parser.nexttext ());} else if ("Apkurl". Equals (Parser.getname ())) {Info.setapkurl (Parser.nexttext ());} break;} Type = Parser.next ();} return info;} catch (Exception e) {e.printstacktrace (); return null;}}}

 
<pre name= "code" class= "HTML" >package com.example.ehrmanager;import java.io.file;import java.io.IOException; Import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.malformedurlexception;import Java.net.url;import Android.app.activity;import Android.app.alertdialog;import Android.app.AlertDialog.Builder; Import Android.app.progressdialog;import Android.content.dialoginterface;import Android.content.dialoginterface.onclicklistener;import Android.content.intent;import Android.content.sharedpreferences;import Android.content.pm.packageinfo;import Android.content.pm.PackageManager ; Import Android.content.pm.packagemanager.namenotfoundexception;import Android.content.res.resources.notfoundexception;import Android.net.uri;import Android.os.Bundle;import Android.os.environment;import Android.os.handler;import Android.os.message;import Android.util.Log;import Android.view.menu;import Android.view.animation.alphaanimation;import Android.widget.textview;import Android.widGet. Toast;import Com.example.ehrmanager.domain.updateinfo;import Com.example.ehrmanager.utils.downloadutil;import Com.example.ehrmanager.utils.updateinfoparser;public class Splashactivity extends Activity {private TextView mtvversion;//Show app version private String mversion;//applied version public static final int parse_xml_error = 10;public static final int PA rse_xml_success = 11;public static final int server_error = 12;public static final int url_error = 13;public static final int network_error = 14;private static final int download_success = 15;private static final int download_error = 16;protect Ed static final String TAG = "splashactivity";p rivate static final int copydata_error = 17;private UpdateInfo updateinfo;p  Rivate progressdialog pd;//Download Progress dialog box Private Handler Handler = new Handler () {public void Handlemessage (android.os.Message msg) {switch (msg.what) {case PARSE_XML_ERROR:Toast.makeText (Getapplicationcontext (), "Parse XML failed", 0). Show ();// Enter the program main interface Loadmainui (); Break;case SERVER_ERROR:Toast.makeTexT (Getapplicationcontext (), "Server Exception", 0). Show ();//Enter Program main interface Loadmainui (); Break;case URL_ERROR:Toast.makeText ( Getapplicationcontext (), "Server address Exception", 0). Show ();//Enter Program main interface Loadmainui (); Break;case NETWORK_ERROR:Toast.makeText ( Getapplicationcontext (), "network exception", 0). Show ();//Enter Program main interface Loadmainui (); Break;case parse_xml_success:if (Getappversion (). Equals (Updateinfo.getversion ())) {//Enter program main interface LOG.I (tag, "version number same, enter main interface"); Loadmainui ();} else {log.i (tag, "version number is not the same, Bounce out the Upgrade prompt dialog box "); Showupdatedialog ();} Break;case DOWNLOAD_ERROR:Toast.makeText (Getapplicationcontext (), "Download Failed", 0). Show ();//Enter Program main interface Loadmainui (); break; Case Download_success:file file = (file) msg.obj; LOG.I (TAG, "install apk" + File.getabsolutepath ());//install apkinstallapk (file); finish (); Break;case Copydata_error: Toast.maketext (Getapplicationcontext (), "Load Database Failed", 0). Show (); break;}};}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Intiviews ();} /** * Initialize component */private void Intiviews () {Setcontentview (R.layout.activity_splash); mtvversion= (TextView) This.findviewbyid (r.id.app_version); mversion=getappversion ();//Get the version of the app Mtvversion.settext (mversion);//The connection server checks for version updates. New Thread (New Checkversiontask ()). Start (); Alphaanimation AA = new Alphaanimation (0.2f, 1.0f); aa.setduration (+); Findviewbyid (R.id.rl_splash). startanimation (AA);} /** * Get App version info * @return App version number */private String getappversion () {Packagemanager pm=getpackagemanager (); PackageInfo info=null;try {info=pm.getpackageinfo (getpackagename (), 0); if (info!=null) {return info.versionname;}} catch (Namenotfoundexception e) {e.printstacktrace ();} Return "";} /** * Enter the main interface */private void Loadmainui () {Intent intent=new Intent (splashactivity.this,homeactivity.class); StartActivity (intent); This.finish ();} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.splash, menu); return true;} /** * Auto-Upgrade prompt dialog box */protected void Showupdatedialog () {Alertdialog.builder Builder = NEW Builder (this); Builder.settitle ("Upgrade reminder"); Builder.setmessage (Updateinfo.getdescription ()); Builder.setpositivebutton ("OK", new Onclicklistener () {@Overridepublic void OnClick (dialoginterface dialog, int which) {String Apkurl = Updateinfo.getapkurl ();pd = new ProgressDialog (splashactivity.this);pd. Settitle ("upgrade operation"); Pd.setmessage ("Downloading ...");pd. Setprogressstyle (Progressdialog.style_horizontal);pd. Show (); LOG.I (TAG, "Install after download:" + apkurl); final file File = new file (Environment.getexternalstoragedirectory (), Downloadutil.getfilename (Apkurl));//Determine if the SD card is available, only the available status. if (Environment.getexternalstoragestate (). Equals ( environment.media_mounted) {new Thread () {public void run () {File savedfile = downloadutil.download ( Updateinfo.getapkurl (), File.getabsolutepath (), PD); Message msg = Message.obtain (); if (savedfile! = null) {//download succeeded Msg.what = Download_success;msg.obj = Savedfile;} else {//down Load Failure msg.what = Download_error;} Handler.sendmessage (msg);pd. Dismiss ();};}. Start ();} else {Toast.maketext (getapplicationconteXT (), "SD card not available", 0). Show (); Loadmainui ();}}); Builder.setnegativebutton ("Cancel", new Onclicklistener () {@Overridepublic void OnClick (dialoginterface dialog, int which) {Loadmainui ();}}); Builder.create (). Show ();//Builder.show ();} Private class Checkversiontask implements Runnable {@Overridepublic void run () {Sharedpreferences sp = Getsharedpreferenc Es ("config", mode_private); Boolean isupdate = Sp.getboolean ("Update", true); if (!isupdate) {try {thread.sleep (1000);} catch (Interruptedexception e) {e.printstacktrace ();} Loadmainui (); return;} Long startTime = System.currenttimemillis (); Message msg = Message.obtain (); try {URL url = new URL (getresources (). getString (R.string.serverurl)); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); conn.setconnecttimeout, int code = Conn.getresponsecode (), if (code = =) {InputStream is = Conn.getinputstream (); UpdateInfo = Updateinfoparser.getupdateinfo (IS); if (updateInfo = = null) {//TODO: Parsing xml failed Msg.what = Parse_xml_error;} else {//parse success msg.what = Parse_xml_success;}} else {//TODO: Server internal error. msg.what = Server_error;}} catch (Malformedurlexception e) {msg.what = Url_error;//Http://e.printStackTrace ();} catch (Notfoundexception e) {MSG.W hat = Url_error; E.printstacktrace ();} catch (IOException e) {msg.what = Network_error;e.printstacktrace ();} finally {long endTime = System.currenttimemillis () ; Long dTime = Endtime-starttime;if (DTime <) {try {thread.sleep (2000-dtime);} catch (Interruptedexception e) { E.printstacktrace ();}} Handler.sendmessage (msg);}}} /** * Install an APK file * * @param the file */protected void installapk (file file) {Intent Intent = new Intent (); Intent.setaction ("an Droid.intent.action.VIEW "), Intent.addcategory (" Android.intent.category.DEFAULT "); Intent.setdataandtype ( Uri.fromfile (file), "application/vnd.android.package-archive"); StartActivity (intent);}}
Tool class Source code:
Download the new apk
<pre name= "code" class= "java" >package com.example.ehrmanager.utils;import Java.io.file;import Java.io.fileoutputstream;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.URL;import Android.app.progressdialog;public class Downloadutil {/** * Download file operation * * @param serverpath * Path to server file * @param s Avedpath * Local saved path * @param PD progress Bar dialog box * @return Download successful return file object download failed return null */public static file download (String SE Rverpath, String Savedpath, ProgressDialog PD) {try {URL url = new URL (serverpath); HttpURLConnection conn = (httpurlconnection) url.openconnection (); conn.setconnecttimeout (5000); Conn.setrequestmethod ("GET"); int code = Conn.getresponsecode (); if (code = =) {Pd.setmax (Conn.getcontentlength ()); I Nputstream is = Conn.getinputstream (); File File = new file (Savedpath); FileOutputStream fos = new FileOutputStream (file), byte[] buffer = new Byte[1024];int len = 0;int total = 0;while (len = i S.read (buffer))! =-1) {fos.write (buffer, 0, Len); total+=len;pd.setprogress (total); Thread.Sleep (20);} Fos.flush (); Fos.close (); Is.close (); return file;} else {return null;}} catch (Exception e) {e.printstacktrace (); return null;}} /** * Gets the name of the server file * @param serverpath * @return */public static string GetFileName (String serverpath) {return serverpath.sub String (Serverpath.lastindexof ("/") +1);}}







Android App Check Update summary

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.