Full parsing of android version updates

Source: Internet
Author: User

Version update is a required function for each project. The idea is similar. First, obtain the Client Version Number to compare with the latest version on the server. If you need to update the version number, return the download link, download and install the Code directly:

MainActivity:

package com.home.update;import android.os.Bundle;import android.app.Activity;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);UpdateManager um = new UpdateManager(MainActivity.this);um.checkUpdateInfo();}}

Tool for version update:

Package com. home. update; import java. io. bufferedReader; import java. io. file; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL; import org. apache. http. httpResponse; import org. apache. http. httpStatus; import org. apache. http. client. clientProtocolEx Ception; import org. apache. http. client. httpClient; import org. apache. http. client. methods. httpGet; import org. apache. http. impl. client. defaultHttpClient; import org. json. JSONException; import org. json. JSONObject; import android. app. alertDialog; import android. app. dialog; import android. app. alertDialog. builder; import android. content. context; import android. content. dialogInterface; import android. content. intent; Import android. content. dialogInterface. onClickListener; import android. content. pm. packageManager. nameNotFoundException; import android.net. uri; import android. OS. environment; import android. OS. handler; import android. OS. message; import android. view. layoutInflater; import android. view. view; import android. view. windowManager; import android. widget. progressBar; public class UpdateManager {private Context cont Ext; // urlprivate final static String CHECKURL = "http ://.... "; // download path of the apk installation package returned by the server: private static String downloadUrl =" "; private Dialog noticeDialog; private ProgressBar mProgress; private boolean interceptFlag = false; private Dialog downloadDialog; private static final int DOWN_UPDATE = 1; private static final int DOWN_OVER = 2; private int progress; // download the package and install the local storage path private static final String sav EPath = Environment. getExternalStorageDirectory () + "/guyun/update/"; private static final String saveFileName = savePath + "sport.apk"; public UpdateManager (Context context) {this. context = context;}/*** update the UI's Handler */private Handler handler = new Handler () {public void handleMessage (Message msg) {switch (msg. what) {case DOWN_UPDATE: mProgress. setProgress (progress); break; case DOWN_OVER: if (downloa DDialog! = Null) downloadDialog. dismiss (); installApk (); break; default: break ;}};/*** version update interface */public void checkUpdateInfo () {// send a check request to the server. if an update is required, the prompt dialog box if (isNeedUpdate () {// display the prompt dialog box showNoticeDialog ();} appears ();}} /*** check whether the current version needs to be updated ** @ return */private boolean isNeedUpdate () {String versionName = getVersionName (context); boolean isNeedUpdate = testVersion (versionName ); return isNeedUpdate;}/*** get the local version name ** @ param Context * @ return */private String getVersionName (Context context) {String versionName = ""; try {// change the package name to the package name that you have applied to. versionName = context. getPackageManager (). getPackageInfo ("com. home. update ", 1 ). versionName;} catch (NameNotFoundException e) {e. printStackTrace ();} return versionName;}/*** initiates a Version Detection request to the server. If the server compares the submitted version parameters with the current version on the server, returns the latest version number and download URL ** @ param versionName * @ return */private boolean. TestVersion (String version) {boolean isNeedUpdate = false; // The url assembly method here should be determined based on the format required by the server. String url = CHECKURL + "? Version = "+ version; String result = get (url); try {// The specific resolution method here should be based on the data returned by your server, JSONObject jsonObj = new JSONObject (result ); int code = jsonObj. getInt ("code"); if (code = 0) {JSONObject valueObj = jsonObj. getJSONObject ("value"); String lastVersion = valueObj. getString ("version"); downloadUrl = valueObj. getString ("url"); if (version. equals (lastVersion) {isNeedUpdate = false;} else {isNeedUpdate = true ;}} Else {isNeedUpdate = false ;}} catch (JSONException e) {e. printStackTrace ();} return isNeedUpdate;}/*** send the request in get mode ** @ param url * @ return */private String get (String url) {BufferedReader reader = null; StringBuffer sb = null; String result = ""; HttpClient client = new DefaultHttpClient (); HttpGet request = new HttpGet (url); request. addHeader ("Content-Type", "text/json"); try {// send the request to get the HttpResponse response Response = client.exe cute (request); // if the request is successful if (response. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK) {reader = new BufferedReader (new InputStreamReader (response. getEntity (). getContent (); sb = new StringBuffer (); String line = ""; while (line = reader. readLine ())! = Null) {sb. append (line) ;}} else if (response. getStatusLine (). getStatusCode () = HttpStatus. SC _SERVICE_UNAVAILABLE) {result = "maintenance or busy" ;}} catch (ClientProtocolException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} finally {try {if (reader! = Null) {reader. close (); reader = null ;}} catch (IOException e) {result = "maintenance or busy"; e. printStackTrace () ;}} if (sb! = Null) {result = sb. toString ();} return result;}/*** the update prompt dialog box */private void showNoticeDialog () {AlertDialog. builder builder = new Builder (context); builder. setTitle ("Software Version Update"); builder. setMessage ("version can be updated"); builder. setPositiveButton ("Download", new OnClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {dialog. dismiss (); showDownloadDialog () ;}}); builder. setNegativeButton ("later", New OnClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {dialog. dismiss () ;}}); noticeDialog = builder. create (); noticeDialog. show (); // set the window manager size attribute in the pop-up dialog box. layoutParams lp = noticeDialog. getWindow (). getAttributes (); lp. width = 400; lp. height = 500; noticeDialog. getWindow (). setAttributes (lp);}/*** download progress dialog box */private void showDownloadDialog () {AlertDialog. builder buil Der = new Builder (context); builder. setTitle ("Download in progress. Please wait... "); final LayoutInflater inflater = LayoutInflater. from (context); View v = inflater. inflate (R. layout. progress, null); mProgress = (ProgressBar) v. findViewById (R. id. progress); builder. setView (v); builder. setNegativeButton ("cancel", new OnClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {dialog. dismiss (); interceptFlag = t Rue ;}}); downloadDialog = builder. create (); downloadDialog. show (); downloadApk ();}/*** start Thread download apk */private void downloadApk () {Thread downLoadThread = new Thread (downApkRunnable); downLoadThread. start ();}/*** installation package download thread */private Runnable downApkRunnable = new Runnable () {@ Overridepublic void run () {try {URL url = new URL (downloadUrl); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); co Nn. connect (); int length = conn. getContentLength (); InputStream is = conn. getInputStream (); File file = new File (savePath); if (! File. exists () {file. mkdir ();} String apkFile = saveFileName; File ApkFile = new File (apkFile); FileOutputStream fos = new FileOutputStream (ApkFile); int count = 0; byte buf [] = new byte [1024]; do {int numread = is. read (buf); count + = numread; progress = (int) (float) count/length) * 100); // Update progress handler. sendEmptyMessage (DOWN_UPDATE); if (numread <= 0) {// the handler is installed after the download is complete. sendEmptyMessage (DOWN_OVER); brea K;} fos. write (buf, 0, numread);} while (! InterceptFlag); // click Cancel to stop the download. fos. close (); is. close ();} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace () ;}};/*** install APK */private void installApk () {File apkfile = new File (saveFileName); if (! Apkfile. exists () {return;} Intent I = new Intent (Intent. ACTION_VIEW); I. setDataAndType (Uri. parse ("file: //" + apkfile. toString (), "application/vnd. android. package-archive "); context. startActivity (I );}}

If the version is later than 4.0, the network cannot be accessed in the main thread. Some functions need to be adjusted accordingly to enable asynchronous subthreads.

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.