This article is for you to share the implementation of the Android app version update feature.
A good application software is a need for good maintenance, from the beginning of the publication to the last boutique, the process needs to update constantly, so how to let users get the first time the latest application installation package? Then we need to implement the upgrade module from the first version of the function.
The principle of automatic update function is that we negotiate with the background of a first interface, we in the application of the main activity, to access this interface, if you need to update, the background will return some data (such as prompt, the latest version of the URL, etc.). Then we give the cue box, the user clicks start the download, the download completes starts to cover the installer, so the user's application keeps up to date the pull.
In order to make it easy for everyone to understand, I prepared a small example as usual, here for convenience I have omitted and the background interaction part. The steps were as follows:
Step One: create a new Android project named: Updatedemo. The code structure is shown in the following illustration
Step Two: Create a new Updatemanager.java class, responsible for the Software update function module, the code is as follows:
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;
Hint language private String updatemsg = "Have the latest software package Oh, kiss fast download it ~";
The installation package URL is returned 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 notify UI refresh handler and MSG constant * * * 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 (msg) {switch (msg.what) {case DOW
N_UPDATE:mProgress.setProgress (progress);
Break
Case down_over:installapk ();
Break
Default:break;
}
};
};
Public Updatemanager {this.mcontext = context;
The//external interface allows the main activity to invoke the 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,
T 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 complete notification installation Mhandler.sendemptymessage (down_over);
Break
} fos.write (Buf,0,numread);
}while (!interceptflag)//Click Cancel to stop downloading.
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 Three: in Mainactivity.java, which is called the main activity, the code is as follows:
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);
Here to detect whether the version needs to be updated
Mupdatemanager = new Updatemanager (this);
Mupdatemanager.checkupdateinfo ();
}
Fourth Step: to add resources and permissions for a program:
download the time to use the ProgressBar, so in advance wrote a progress.xml layout file, the 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"
android:layout_width= "Fill_parent"
Wrap_content "
style=" android:attr/progressbarstylehorizontal "
/>
</LinearLayout>
When downloading the network section, so to add network permissions in Androidmanifest.xml, the code is as follows:
<uses-permission android:name= "Android.permission.INTERNET"/>
Step Fifth: run the viewing effect as follows:
Figure I: Hint with the latest package
Figure Two. Click to start the download
Figure three. After downloading the installation, I have not enough simulator space here.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.