How to Implement the automatic update function of Android software

Source: Internet
Author: User

I believe that all users have encountered Software Update reminders. This function will be implemented below

First, let's take a look at the program directory structure.

Steps:

1. Create an UpdateManger class to display the update prompt.

Copy codeThe Code is as follows: public class UpdateManger {
// Application Context
Private Context mContext;
// Prompt message
Private String updateMsg = "you have the latest software package. Please download it! ";
// Download the network path of the installation package
Private String apkUrl = "http://softfile.3g.qq.com: 8080/msoft/179/24659/43549/qq_hd_mini_1.4.apk ";
Private Dialog noticeDialog; // a prompt box Indicating software update is displayed.
Private Dialog downloadDialog; // Download Dialog Box
Private static final String savePath = "/sdcard/updatedemo/"; // Save the apk folder
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; // current progress
Private Thread downLoadThread; // download Thread
Private boolean interceptFlag = false; // The user cancels the download.
// Handler of the notification processing refresh Interface
Private Handler mHandler = new Handler (){
@ SuppressLint ("HandlerLeak ")
@ Override
Public void handleMessage (Message msg ){
Switch (msg. what ){
Case DOWN_UPDATE:
MProgress. setProgress (progress );
Break;
Case DOWN_OVER:
InstallApk ();
Break;
}
Super. handleMessage (msg );
}
};
Public UpdateManger (Context context ){
This. mContext = context;
}
// Display the update program dialog box for the main program to call
Public void checkUpdateInfo (){
ShowNoticeDialog ();
}
Private void showNoticeDialog (){
Android. app. AlertDialog. Builder builder = new android. app. AlertDialog. Builder (
MContext); // Builder. You can use this builder to change the default theme style and Attribute-related information of AleartDialog.
Builder. setTitle ("Software Version Update ");
Builder. setMessage (updateMsg );
Builder. setPositiveButton ("Download", new OnClickListener (){
@ Override
Public void onClick (DialogInterface dialog, int which ){
Dialog. dismiss (); // when the dialog box is canceled, do you want to operate the code? Cancel dialog box
ShowDownloadDialog ();
}
});
Builder. setNegativeButton ("later", new OnClickListener (){
@ Override
Public void onClick (DialogInterface dialog, int which ){
Dialog. dismiss ();
}
});
NoticeDialog = builder. create ();
NoticeDialog. show ();
}
Protected void showDownloadDialog (){
Android. app. AlertDialog. Builder builder = new android. app. AlertDialog. 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); // set the content of the dialog box to a View
Builder. setNegativeButton ("cancel", new OnClickListener (){
@ Override
Public void onClick (DialogInterface dialog, int which ){
Dialog. dismiss ();
InterceptFlag = true;
}
});
DownloadDialog = builder. create ();
DownloadDialog. show ();
DownloadApk ();
}
Private void downloadApk (){
DownLoadThread = new Thread (mdownApkRunnable );
DownLoadThread. start ();
}
Protected 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"); // File. toString () will return the path information
MContext. startActivity (I );
}
Private Runnable mdownApkRunnable = new Runnable (){
@ Override
Public void run (){
URL url;
Try {
Url = new URL (apkUrl );
HttpURLConnection conn = (HttpURLConnection) url. openConnection ();
Conn. connect ();
Int length = conn. getContentLength ();
InputStream ins = conn. getInputStream ();

File file = new File (savePath );
If (! File. exists ()){
File. mkdir ();
}
String apkFile = saveFileName;
File ApkFile = new File (apkFile );
FileOutputStream outStream = new FileOutputStream (ApkFile );
Int count = 0;
Byte buf [] = new byte [1024];
Do {
Int numread = ins. read (buf );
Count + = numread;
Progress = (int) (float) count/length) * 100 );
// Download progress
MHandler. sendEmptyMessage (DOWN_UPDATE );
If (numread <= 0 ){
// Download completion notification Installation
MHandler. sendEmptyMessage (DOWN_OVER );
Break;
}
OutStream. write (buf, 0, numread );
} While (! InterceptFlag); // click Cancel to stop the download.
OutStream. close ();
Ins. close ();
} Catch (Exception e ){
E. printStackTrace ();
}
}
};
}

2. Create an xml file to define the progress of the ProgressBar during the download process, named progress. xml
Copy codeThe Code is as follows: <? 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. Check for software updates in the onCreate () method of MainActivity

MUpdateManger = new UpdateManger (MainActivity. this); // note that getApplicationContext () cannot be input here; an error is returned because only one Activity can add a form.
MUpdateManger. checkUpdateInfo ();

And add the network permission to the configuration list file <uses-permission android: name = "android. permission. INTERNET"/>

4. Run the program

-- Click to download -->

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.