Implementation of the Android app auto update function

Source: Internet
Author: User

A good application software requires good maintenance. From the initial publication to the final product, this process requires constant updates of the version. So how can users get the latest application installation package immediately? Therefore, we need to upgrade the module from the first version.

The implementation principle of the automatic update function is that we negotiate an interface with the background in advance. We access this interface in the main Activity of the application. If you need to update the interface, the background will return some data (such as prompts and the latest url ). In the prompt box, click Start download to overwrite the installer after the download is complete, so that your application remains up to date.

To make it easy for everyone to understand, I have prepared a small example as usual. For convenience, I am saving the time to interact with the background. The steps are as follows:

Step 1: Create an Android project named UpdateDemo. The code structure is shown in:

 


 

Step 2: Create an UpdateManager. java class to update the software module. The Code is as follows:

[Java] package com. tutor. update;
 
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 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.net. Uri;
Import android. OS. Handler;
Import android. OS. Message;
Import android. view. LayoutInflater;
Import android. view. View;
Import android. widget. ProgressBar;
 
Public class UpdateManager {
 
Private Context mContext;

// Prompt
Private String updateMsg = "you have the latest software package. Download it now ~ ";

// Url of the returned installation package
Private String apkUrl = "http://softfile.3g.qq.com: 8080/msoft/179/24659/43549/qq_hd_mini_1.4.apk ";


Private Dialog noticeDialog;

Private Dialog downloadDialog;
/* Download package installation path */
Private static final String savePath = "/sdcard/updatedemo /";

Private static final String saveFileName = savePath + "UpdateDemoRelease.apk ";
 
/* Progress bar and handler and msg constants that notify the ui to refresh */
Private ProgressBar mProgress;
 

Private static final int DOWN_UPDATE = 1;

Private static final int DOWN_OVER = 2;

Private int progress;

Private Thread downLoadThread;

Private boolean interceptFlag = false;

Private Handler mHandler = new Handler (){
Public void handleMessage (Message msg ){
Switch (msg. what ){
Case DOWN_UPDATE:
MProgress. setProgress (progress );
Break;
Case DOWN_OVER:

InstallApk ();
Break;
Default:
Break;
}
};
};

Public UpdateManager (Context context ){
This. mContext = context;
}

// External interface for the main Activity to call
Public void checkUpdateInfo (){
ShowNoticeDialog ();
}


Private void showNoticeDialog (){
AlertDialog. Builder builder = new Builder (mContext );
Builder. setTitle ("Software Version Update ");
Builder. setMessage (updateMsg );
Builder. setPositiveButton ("Download", new OnClickListener (){
@ Override
Public void onClick (DialogInterface dialog, int which ){
Dialog. dismiss ();
ShowDownloadDialog ();
}
});
Builder. setNegativeButton ("later", new OnClickListener (){
@ Override
Public void onClick (DialogInterface dialog, int which ){
Dialog. dismiss ();
}
});
NoticeDialog = builder. create ();
NoticeDialog. show ();
}

Private void showDownloadDialog (){
AlertDialog. Builder builder = new Builder (mContext );
Builder. setTitle ("Software Version Update ");

Final LayoutInflater inflater = LayoutInflater. from (mContext );
View v = inflater. inflate (R. layout. progress, null );
MProgress = (ProgressBar) v. findViewById (R. id. progress );

Builder. setView (v );
Builder. setNegativeButton ("cancel", new OnClickListener (){
@ Override
Public void onClick (DialogInterface dialog, int which ){
Dialog. dismiss ();
InterceptFlag = true;
}
});
DownloadDialog = builder. create ();
DownloadDialog. show ();

DownloadApk ();
}

Private Runnable mdownApkRunnable = new Runnable (){
@ Override
Public void run (){
Try {
URL url = new URL (apkUrl );

HttpURLConnection conn = (HttpURLConnection) url. openConnection ();
Conn. 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
MHandler. sendEmptyMessage (DOWN_UPDATE );
If (numread <= 0 ){
// Download completion notification Installation
MHandler. sendEmptyMessage (DOWN_OVER );
Break;
}
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 ();
}

}
};

/**
* Download apk
* @ Param url
*/

Private void downloadApk (){
DownLoadThread = new Thread (mdownApkRunnable );
DownLoadThread. start ();
}
/**
* Install apk
* @ Param url
*/
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 ");
MContext. startActivity (I );

}
}

Step 3: Call MainActivity. java, that is, the main Activity. The Code is as follows: [java] package com. tutor. update;
 
Import android. app. Activity;
Import android. OS. Bundle;
 
Public class MainAcitivity extends Activity {

 
Private UpdateManager mUpdateManager;
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );

// Check whether the version needs to be updated.
MUpdateManager = new UpdateManager (this );
MUpdateManager. checkUpdateInfo ();
}
}

Step 4: add the resources and permissions used by the Program:
The ProgressBar is used for downloading, so a progress. xml layout file is written in advance. The Code is as follows:

[Java] <? 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"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Style = "? Android: attr/progressBarStyleHorizontal"
/>
</LinearLayout>
The Network part is used during the download, so you need to go to AndroidManifest. add the network permission in xml. The Code is as follows: [java] <uses-permission android: name = "android. permission. INTERNET "/>

Step 5: view the running result as follows:

Figure 1: The latest package is displayed. Figure 2: Click to download

Figure 3: Installation starts after the download. The simulator space is insufficient here.
 
Source code download: http://www.bkjia.com/uploadfile/2012/0409/20120409023126122.rar



From the treasure Valley

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.