Android easily supports background building + APP version update, and androidapp

Source: Internet
Author: User

Android easily supports background building + APP version update, and androidapp

(This article describes how to update the APP version in Android. The source code is included at the end of this Article .)

After reading this article, you can learn:
1. Version update Method

2. Interaction with the background

3. Handler usage in Android

4. Use of ProgressDialog in Android

Let's take a look:





I. general ideas
First, we need a background that can be accessed by a mobile phone. Here we have Two methods, We can use Connect your mobile phone and laptop to the same LANTo enable a background service similar to PHP or JAVAEE on the computer. However, if you have no background development experience Better Way: Using Github, etc. Free Space. For details, please stamp my other blog post and use Github to build your personal website. OK. What do we want to put in the background that stores resources? It is very simple. The update.txt file with the latest upload information and a .apk FileEnough!
What is written in a txt file? Let's take a look at my example:XXX & 1.3 & here description & http: // 192.168.1.100: 8080/PersonalHomePage/new.apk
Explanations: & Is a SeparatorUsed to split the information obtained by the mobile phone end. 1.3 represents the latest version, Which is Description of the new versionAnd finally The new version of APK(I used a LAN here ). What was it at the beginning? At the time of the experiment, I did not add additional information at the beginning, that is, I started with 1.3. After the experiment, I found that the text on the mobile phone could not be correctly parsed after obtaining the TXT text information, I think the reason is that the TXT file contains some built-in characters at the beginning, which may cause problems during parsing on the mobile phone. (If you are interested, you can go further and hope to give me some advice !)
OK. What should we do with the new version?We need to get the latest version number and compare it with the current APP version number. If the version is earlier than the latest version, download it.
Ii. Detailed code explanation
First, create an updateinfocategory to correspond to the content of update.txt. This 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 obtain new information, that is, 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 = GetServerUrl. getUrl () + "/update.txt"; StringBuffer sb = new StringBuffer (); St Ring line = null; BufferedReader reader = null; try {// create a url object URL = new url (path); // pass through the URL object, create an HttpURLConnection object (connection) HttpURLConnection urlConnection = (HttpURLConnection) url. openConnection (); // obtain InputStreamreader = new BufferedReader (new InputStreamReader (urlConnection. getInputStream (); // use the 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. printStackTrace () ;}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 ;}}

Here, you can first create an HttpURLConnection and then obtain the input stream. Careful friends 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 am using a local JAVAEE project. You can modify it based on your actual situation. Public static String getUrl () {return url ;}}

OK, at this step, All preparations have been completed., There is only one class left! That is, our MainActicity. There are more than one hundred rows in total. Let's talk about it in several parts.
The first part of the code is to obtain version update information.
Public class MainActivity extends Activity {// information required for updating the version private UpdateInfo info; private ProgressDialog pBar; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); Toast. makeText (MainActivity. this, "checking version updates .. ", Toast. LENGTH_SHORT ). show (); // automatically check whether there is a new version. If there is a new version, the system prompts to update new 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) {// if there is any update, the prompt is if (isNeedUpdate () {// In the following code snippet showUpdateDialog (); // the following code snippet }};};

Here we use the new Thread + Handler method to asynchronously Load version information, mainly because the time-consuming tasks should be executed in a non-main Thread in Android, otherwise it will cause blocking, throw a non-response exception. Another implementation method is Android-encapsulated AsyncTask. For details, refer to this blog post: Android AsyncTask.

In the second part, check whether the latest version is available. If not, select whether to update in the displayed dialog box:
Private void showUpdateDialog () {AlertDialog. builder builder = new AlertDialog. builder (this); builder. setIcon (android. r. drawable. ic_dialog_info); builder. setTitle ("upgrade the 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 (); // code segment} else {Toast. makeText (MainActivity. this, "SD card unavailable, 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 (); // Log of the latest version. I ("update", v); Toast. makeText (MainActivity. this, v, Toast. LENGTH_SHORT ). show (); if (v. equals (getVersion () {return false;} else {return true ;}// obtain the current version number private String getVersion () {try {PackageManager packageManager = getPackageManager (); PackageInfo packageInfo = packageManager. getPackageInfo (getPackageName (), 0); return packageInfo. versionName;} catch (NameNotFoundException e) {e. printStackTrace (); return "unknown version number ";}}
In this section, you must note how to obtain the current version by using the getPackageInfo method provided by PackageManager and the version number in the manifest file is returned. Other codes are quite simple and fully annotated. If you have any questions, please leave a message.
Next is the last part. download the file.
Void downFile (final String url) {pBar = new ProgressDialog (MainActivity. this); // progress bar, which updates the progress in real time during download to improve user friendliness. setProgressStyle (ProgressDialog. STYLE_HORIZONTAL); pBar. setTitle ("downloading"); pBar. setMessage ("Please wait... "); pBar. setProgress (0); pBar. show (); new Thread () {public void run () {HttpClient client = new DefaultHttpClient (); HttpGet get = new HttpGet (url); HttpResponse response; try {response = client.exe cut E (get); HttpEntity entity = response. getEntity (); int length = (int) entity. getContentLength (); // obtain 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, I read 10 bits at a time, and I got a little small point. Because it is local, the download is finished when the value is too large, and I cannot see the progressbar effect. Int ch =-1; int process = 0; while (ch = is. read (buf ))! =-1) {fileOutputStream. write (buf, 0, ch); process + = 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, which is usually written in void update () {Intent intent = new Intent (Intent. ACTION_VIEW); intent. setDataAndType (Uri. fromFile (new File (Environment. getExternalStorageDirectory (), "Test.apk"), "application/vnd. android. package-archive "); startActivity (intent );}
This section mainly uses progressdialog to update the progress in real time during download, and mainly uses the buffer zone of a byte array. That is, each time the obtained content fills the buffer, it is written to the local file. Here, I set the buffer size to 10 bytes (1024 will be better). The reason is that the speed in the same LAN is very fast, and the download is complete after a click, and the progress bar is not displayed, when the buffer is adjusted to a smaller value, it will be OK.

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

Written below:

The source code has been uploaded to my Github, or to the CSDN Download Area.

For any questions, please leave a message!



Related Article

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.