Android easy to implement background build +app version update

Source: Internet
Author: User

(This article explains the app version update in Android, with the source code at the end of the text.) )

After reading this article, you can learn:
1. How to update the version

2. Interacting with the background

Use of handler in 3.Android

Use of ProgressDialog in 4.Android

Talk not much, first look at:





First, the general idea elaborated
First, we need to have a background that can be accessed by a mobile phone. Here are two different methods, we can use it during commissioning. phone and notebook connected to the same LANWay, on the computer to open a similar PHP or Java EE-like background services. But for friends who have no background development experience, there's a a better way: Using GitHub, etc. Free SpaceTo achieve. For more details please poke my other blog post using GitHub to build your personal site. OK, there is the background of storage resources, we have to put something? Very simple, a the Update.txt file with the latest version information and an. apk fileThat's enough!
what does the txt file say? Take a look at my example:xxx&1.3& here to write some description &http://192.168.1.100:8080/personalhomepage/new.apk
Explain: & is a delimiter, which is used for segmentation after the mobile phone gets the information. 1.3 Represents the latest version number, followed by description of the new version, the last is new version of APK(I use a local area network here). What was it at the beginning? I was in the experiment, at the beginning and did not add additional information, that is, starting with 1.3, after the experiment, found that the phone to obtain the TXT text message can not be parsed correctly, because I think it is because the beginning of the TXT file contains some of the characters, the phone parsing will be problematic. (Interested friends can go to the deep, but also look at the Liberal enlighten!) )
OK, with the new version of the information, what do we do? We want to get the latest version number and then compare it to the version number of the current app. If it is below the latest version, go to the download.
Second, detailed code explanation
First, create a new Updateinfo class that corresponds to the contents of the Update.txt, which is simple:
Package Com.example.appupdatedemo;public class updateinfo{        private String version;        Private String description;        Private String URL;                Public String getversion ()        {                return version;        }        public void Setversion (String version)        {                this.version = version;        }        Public String getdescription ()        {                return description;        }        public void SetDescription (String description)        {                this.description = description;        }        Public String GetUrl ()        {                return URL;        }        public void SetUrl (String url)        {                this.url = URL;        }        }


Then, write a class to get the updated information, namely our Update.txt file:
Updateinfoservice:

Package Com.example.appupdatedemo;import Java.io.bufferedreader;import Java.io.inputstreamreader;import Java.net.httpurlconnection;import Java.net.url;import Android.content.context;public class UpdateInfoService { Public Updateinfoservice (Context context) {}public UpdateInfo getupdateinfo () throws Exception {String path = Getserverur L.geturl () + "/update.txt"; StringBuffer sb = new StringBuffer (); String line = null; BufferedReader reader = null;try {//Create a URL object url url = new URL (path);//through the URL object, Create a HttpURLConnection object (connection) httpurlconnection URLConnection = (httpurlconnection) url.openconnection ();// By HttpURLConnection object, get InputStreamReader = new BufferedReader (New InputStreamReader (Urlconnection.getinputstream ( ));//Use IO stream to read the file while (line = Reader.readline ())! = null) {sb.append (line);}} catch (Exception e) {e.printstacktrace ();} finally {try {if (reader! = null) {Reader.close ();}} catch (Exception e) {E.pri Ntstacktrace ();}} String info = sb.tostring (); UpdateInfo UpdateInfo = new UpdateinFo (); Updateinfo.setversion (Info.split ("&") [1]); Updateinfo.setdescription (Info.split ("&") [2]); Updateinfo.seturl (Info.split ("&") [3]); return updateInfo;}}

The way to get the file here is to first create a httpurlconnection and then get the input stream. A careful friend may notice that there is a class called Getserverurl, which is used to store the background address information:
Package com.example.appupdatedemo;/** * Get server IP address */public class getserverurl{static String url= "/http/ 192.168.1.100:8080/personalhomepage ";   Yes, I use the local Java EE project here, you have to change according to the actual situation. public static String GetUrl () {return URL;}}

OK, at this step, the preparations are done., then there's only one class left! That is, our mainacticity, altogether more than 100 lines, we are divided into several parts.
The first part of the code that does the job is to get the version update information.
public class Mainactivity extends Activity {//update version to be used for some information private UpdateInfo info;private ProgressDialog pbar;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Toast.maketext (Mainactivity.this, "Checking for version update:", Toast.length_short). Show ();//Auto Check for new version if new version is prompted for update Thread () { public void Run () {try {updateinfoservice updateinfoservice = new Updateinfoservice (mainactivity.this); info = Updateinfoservice.getupdateinfo (); handler1.sendemptymessage (0);} catch (Exception e) {e.printstacktrace ();}};}. Start ();} @SuppressLint ("Handlerleak") private Handler handler1 = new Handler () {public void Handlemessage (Message msg) {//Prompt if there is an update if (Isneedupdate ()) {   //In the code snippet below Showupdatedialog ();  The following code snippet}};

Here we use the new thread+ handler way to do the asynchronous load version information, mainly because the time-consuming task in Android to be executed in the non-main thread, otherwise it will cause blocking, throw no response exception. There is another way to achieve this is the Android package Asynctask, specifically refer to this blog post: Android asynctask detailed.

The second part, determine whether the latest version, if not, jump out of the dialog box to choose whether to update:
private void Showupdatedialog () {Alertdialog.builder Builder = new Alertdialog.builder (this); Builder.seticon (Android. R.drawable.ic_dialog_info) Builder.settitle ("Please upgrade app to version" + info.getversion ()); Builder.setmessage ( Info.getdescription ()); builder.setcancelable (false); Builder.setpositivebutton ("OK", new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (dialoginterface dialog, int which) {if (     Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {Downfile (Info.geturl ()); In the following code snippet} else {Toast.maketext (mainactivity.this, "SD card is not available, please insert SD card", Toast.length_short). Show ();}}); Builder.setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (dialoginterface dialog, int which) {}}); Builder.create (). Show (); Private Boolean isneedupdate () {String v = info.getversion ();//The version number of the latest version log.i ("Update", V); Toast.maketext (Mainactivity.this, V, Toast.length_short). Show (); if (V.equals (GetVersion ())) {return false;} else { return true;}} Get Current versionThe version number of private String getversion () {try {Packagemanager Packagemanager = Getpackagemanager (); PackageInfo PackageInfo = Packagemanager.getpackageinfo (Getpackagename (), 0); return packageinfo.versionname;} catch (Namenotfoundexception e) {e.printstacktrace (); return "version number Unknown";}}
The note in this paragraph is how to get the current version by using the Getpackageinfo method provided by Packagemanager, which returns the version number in the manifest file. The other code is quite simple, and the annotations are quite complete. If you have any questions, please leave a message.
Next is the last part to download the file.
void Downfile (final String url) {pBar = new ProgressDialog (mainactivity.this); Progress bar, update the progress in real-time when downloading, improve user-friendliness Pbar.setprogressstyle (progressdialog.style_horizontal);p bar.settitle ("Downloading");  Pbar.setmessage ("Please wait ...");p bar.setprogress (0);p bar.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 (); int length = (int) entity.getcontentlength ();                            Gets the file size Pbar.setmax (length); Set the total length of the progress bar inputstream is = Entity.getcontent (); FileOutputStream FileOutputStream = Null;if (is! = null) {File File = new file (Environment.getexternalstoragedirectory (),   "test.apk"); FileOutputStream = new FileOutputStream (file); byte[] buf = new BYTE[10]; This is a buffer, that is, read 10 bits at a time, I made a little bit, because in the local, so the value is too large to download, see the effect of ProgressBar. int ch = -1;int Process = 0;while ((ch = is.read (BUF))! =-1) {FileoUtputstream.write (buf, 0, ch);p rocess + = ch;pbar.setprogress (process); Here is the key real-time update progress! }}fileoutputstream.flush (); if (fileoutputstream! = null) {Fileoutputstream.close ();} Down ();} catch (Clientprotocolexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();}}}. Start ();} void Down () {Handler1.post (new Runnable () {public void run () {pbar.cancel (); Update ();});} Installation file, general fixed notation void Update () {Intent Intent = new Intent (Intent.action_view); Intent.setdataandtype (uri.f Romfile (New File (Environment.getexternalstoragedirectory (), "test.apk")), "application/ Vnd.android.package-archive "); StartActivity (intent);}
This section mainly utilizes ProgressDialog to update the progress in real time while downloading, mainly using the buffer of a byte array. That is, each time the captured content fills the buffer, it is written to the local piece. Here I set the size of the buffer to 10 bytes (1024 will be better), the reason is because in the same local area network speed particularly fast, brush the download is finished, see the progress bar effect, buffer small point on OK.

========================================

Write in the back:

The source code has been uploaded to my github, or downloaded to the CSDN download area.

Any questions, welcome message exchange!



Android easy to implement background build +app version update

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.