Automatic update-download the apk and the implementation of the prompt dialog box (3), and automatically update the apk

Source: Internet
Author: User

Automatic update-download the apk and the implementation of the prompt dialog box (3), and automatically update the apk

Download apk and implementation of prompt dialog box

1. steps:

1. confirm that a version can be updated. The dialog box reminds you whether to update the version.

2. If you select update, the download dialog box is displayed and downloaded. Otherwise, the update prompt dialog box is closed.

3. After the Apk is downloaded, install the apk.

Ii. Details:

1. When a user is prompted to update, the method to implement the update must be as follows: only the update button is displayed in the displayed dialog box, that is, only the update button can be selected.

2. During the download, a progress bar is displayed on the page of the download dialog box to display the download progress.

3. Start a subthread to download the SDK.

4. The Source Path and saved path are required during download.

5. In the download dialog box, the cancel button is displayed. When you click Cancel to cancel the download, you can directly stop reading data from the download process.

6. The progress bar of the download dialog box is updated in real time. Therefore, communication between the main thread and sub-thread is required. The communication is implemented using the Handler class.

7. During communication, install the apk when sending the download signal.

8. Use intent for installation.

3. The Code is as follows:

1. Main Code

Import java. io. file; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStream; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL; import net. aufo. apps. certclient. r; import android. app. activity; import android. app. alertDialog; import android. app. alertDialog. builder; import android. app. dialog; import android. content. context; import android. Content. dialogInterface; import android. content. dialogInterface. onClickListener; import android. content. intent; 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. widget. progressBar; public class UpdateManager {/* DOWNLOAD */private static final int DOWNLOAD = 1;/* DOWNLOAD complete */private Static final int DOWNLOAD_FINISH = 2; private String downloadUrl;/* download save path */private String localSavePath;/* record progress bar quantity */private int progress; /* cancel update */private boolean cancelUpdate = false; private Context mContext;/* update progress bar */private ProgressBar mProgress; private Dialog mDownloadDialog; private Handler mHandler = new Handler () {public void handleMessage (Message msg) {switch (msg. what) {// download case DOWN LOAD: // set the progress bar position mProgress. setProgress (progress); break; case DOWNLOAD_FINISH: // Installation File installApk (); break; default: break ;}}; public UpdateManager (Context context) {this. mContext = context;}/*** display software update dialog box */public void showNoticeDialog (boolean forceUpdate, String updatedDetail, String downloadUrl, String localSavePath) {this. downloadUrl = downloadUrl; this. localSavePath = localSavePath; // structure dialog box AlertDialog. Builder builder = new Builder (mContext); builder. setTitle ("Software Update"); builder. setMessage (updatedDetail); // update builder. setPositiveButton ("Update", new OnClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {dialog. dismiss (); // display the Download Dialog Box showDownloadDialog () ;}}); if (forceUpdate = false) {// update builder later. setNegativeButton ("updated later", new OnClickListener () {@ Overridepublic void onClick (DialogInt Erface dialog, int which) {dialog. dismiss ();/* dialog. dismiss (); (Activity) mContext ). finish (); System. exit (0); */});} Dialog noticeDialog = builder. create (); noticeDialog. show ();}/*** show Software Download Dialog Box */private void showDownloadDialog () {// create a Software Download Dialog Box AlertDialog. builder builder = new Builder (mContext); builder. setTitle ("downloading updates"); // Add the progress bar final LayoutInflater inflater = LayoutInflater to the download dialog box. from (mContext); View v = Inflater. inflate (R. layout. progress, null); mProgress = (ProgressBar) v. findViewById (R. id. progress); builder. setView (v); // cancel the builder update. setNegativeButton ("cancel", new OnClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {dialog. dismiss (); // set the canceled state cancelUpdate = true ;}}); mDownloadDialog = builder. create (); mDownloadDialog. show (); // start a new thread to download the software new downloadApkThread (). start ();}/** * Download file Thread */private class downloadApkThread extends Thread {@ Overridepublic void run () {try {// determine whether the SD card exists and whether it has the read/write permission if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {URL url = new URL (downloadUrl); // creates a connection HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. connect (); // get the file size int length = conn. getContentLength (); // create the input stream InputStream is = conn. getInputStream (); File file = new File (localSavePath); // checks whether the File directory exists if (! File. exists () {file. mkdirs ();} File apkFile = new File (localSavePath, "update.apk"); FileOutputStream fos = new FileOutputStream (apkFile); int count = 0; // cache byte buf [] = new byte [1024]; // write to the file do {int numread = is. read (buf); count + = numread; // calculate the progress bar position progress = (int) (float) count/length) * 100); // update the progress of mHandler. sendEmptyMessage (DOWNLOAD); if (numread <= 0) {// DOWNLOAD completed mHandler. sendEmptyMessage (DOWNLOAD _ FINISH); break;} // write the file fos. write (buf, 0, numread);} while (! CancelUpdate); // click Cancel to stop the download. fos. close (); is. close () ;}} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} // The cancel download dialog box displays mDownloadDialog. dismiss () ;}};/*** install APK File */private void installApk () {File apkfile = new File (localSavePath, "update.apk"); if (! Apkfile. exists () {return;} // install the APK file Intent I = new Intent (Intent. ACTION_VIEW); I. setDataAndType (Uri. parse ("file: //" + apkfile. toString (), "application/vnd. android. package-archive "); mContext. startActivity (I );}}


 

2. Download the code progress. xml in the dialog box

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content" >    <ProgressBar        android:id="@+id/progress"        style="?android:attr/progressBarStyleHorizontal"        android:layout_width="fill_parent"        android:layout_height="wrap_content" /></LinearLayout>


 

3. Call Code

UpdateManager update = new UpdateManager (this); update. showNoticeDialog (false, "is the new version detected? update now? "," Http://saifusuozheng.dbankcloud.com/AppGenXin/CertClient.apk ", getFilesDir (). getPath ());


 

Iv. Reference website:

1. Update Procedure

Http://www.iteye.com/problems/55470

2. xml parsing and generation

Http://developer.51cto.com/art/200903/117512.htm

3. Get the file http://blog.csdn.net/blueman2012/article/details/6450895 from the network

4. Android automatic update program

4.1 http://www.cnblogs.com/wainiwann/archive/2012/03/12/2391810.html

4.2 http://www.cnblogs.com/coolszy/archive/2012/04/27/2474279.html

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.