An example of Android update module and Automatic Update module

Source: Internet
Author: User
Tags getmessage

This article introduces the principle of implementation, in order to use conveniently, a simple encapsulation of a class updater. The usage is very simple. Well, in order to support multiple languages, it's still a little cumbersome.

Usage:

Character definitions used in Strings.xml
Other languages to add themselves, the following instance programs in both English and Chinese have

The code is as follows Copy Code

<string name= "Update" >check for update</string>
<string name= "Help" >Help?</string>
<string name= "Help_content" >i am helper,muhaha~~~</string>
<string name= "Found_newversion" >found a new version</string>
<string name= "Need_update" >need update?</string>
<string name= "Alertdialog_title" >software update</string>
<string name= "Alertdialog_update_button" >Update</string>
<string name= "Alertdialog_cancel_button" >not now</string>
<string name= "Progressdialog_title" >downloading update</string>
<string name= "Progressdialog_message" >please wait a moment</string>

Permissions to be used to add updates in Androidmanifest.xml

The code is as follows Copy Code
<uses-permission android:name= "Android.permission.INTERNET" ></uses-permission>
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
<uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS" ></uses-permission>
<uses-permission android:name= "Android.permission.INSTALL_PACKAGES" ></uses-permission>

Check for updates and pop-up prompts if a new version is found

The code is as follows Copy Code
Private Boolean checkupdate () {
Updater Updater = new Updater ("HTTP://127.0.0.1/", this);
if (Updater.needupdate ())//found update
Updater.shownewversionupdate ();
else {

}

return true;
}

Automatic Updates


An Android app that you've been customizing for someone else needs an automatic update. The application in Market is not something to worry about, but custom programs like mine need to be implemented on their own.

The principle is fairly simple, when checking for updates, get server-side version information through the specified URL. Compare versions, if updated, Access server-side returned apk URL address, download, install. A variety of makert are also achieved through similar mechanisms. The principle is clear, the code is quite simple.

Gets the vesionname of the APK, that is, the android:versionname defined in Androidmanifest.xml

The code is as follows Copy Code

Public String Getvesionname (context context) {
String versionname = null;
try {
Versionname = Context.getpackagemanager (). Getpackageinfo ("Net.vpntunnel", 0). Versionname;
catch (Namenotfoundexception e) {
LOG.E (TAG, E.getmessage ());
}

return versionname;
}

Updates and the permissions required by the installer, adding in Androidmanifest.xml

The code is as follows Copy Code
<uses-permission android:name= "Android.permission.INTERNET" ></uses-permission>
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
<uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS" ></uses-permission>
<uses-permission android:name= "Android.permission.INSTALL_PACKAGES" ></uses-permission>

Gets the versioncode of the APK, that is, the Android:versioncode defined in Androidmanifest.xml

The code is as follows Copy Code

public int Getversioncode (context context) {
int versioncode = 0;
try {
Versioncode = Context.getpackagemanager (). Getpackageinfo ("Net.vpntunnel", 0). Versioncode;
catch (Namenotfoundexception e) {
LOG.E (TAG, E.getmessage ());
}

return versioncode;
}

Server-side version. JSON, containing APK path and version information

The code is as follows Copy Code

{
"Apkname": "NAME",
"Apkfullname": "name_1.0.5.apk",
"Versionname": "1.0.5",
"Versioncode": 3
}

Get version information for a remote server

The code is as follows Copy Code

private void Getremotejson (String host) throws Clientprotocolexception, IOException, jsonexception {
String url = String.Format ("http://%s/%s", host, Ver_json);
StringBuilder sb = new StringBuilder ();
HttpClient client = new Defaulthttpclient ();
Httpparams httpparams = Client.getparams ();
Httpconnectionparams.setconnectiontimeout (Httpparams, 3000);
Httpconnectionparams.setsotimeout (Httpparams, 5000);
HttpResponse response = Client.execute (new HttpGet (URL));
httpentity entity = response.getentity ();
if (entity!= null) {
BufferedReader reader = new BufferedReader (New InputStreamReader (Entity.getcontent (), "UTF-8"), 8192);

String line = null;
while (line = Reader.readline ())!= null) {
Sb.append (line + "n");
}
Reader.close ();
}

Jsonobject object = (jsonobject) New Jsontokener (Sb.tostring ()). NextValue ();
This.apkfullname = object.getstring ("Apkfullname");
This.versionname = object.getstring ("Versionname");
This.versioncode = integer.valueof (Object.getint ("Versioncode"));
}

Discovery of updated Reminders window, implemented through Alertdialog

The code is as follows Copy Code

private void Shoversionupdate (String newversion, final string updateurl) {
String message = String.Format ("%s:%s,%s", Mcontext.getstring (r.string.found_newversion), NewVersion, Mcontext.getstring (r.string.need_update));
Alertdialog dialog = new Alertdialog.builder (mcontext). Settitle (Mcontext.getstring (R.string.alertdialog_title)). Setmessage (Message)
Update
. Setpositivebutton (Mcontext.getstring (R.string.alertdialog_update_button), New Dialoginterface.onclicklistener () {
@Override
public void OnClick (Dialoginterface dialog, int which) {
Pbar = new ProgressDialog (mcontext);
Pbar.settitle (mcontext.getstring (r.string.progressdialog_title));
Pbar.setmessage (mcontext.getstring (r.string.progressdialog_message));
Pbar.setprogressstyle (Progressdialog.style_spinner);
Dialog.dismiss ();
Downfile (UpdateUrl);
}
Cancel
}). Setnegativebutton (Mcontext.getstring (R.string.alertdialog_cancel_button), new Dialoginterface.onclicklistener () {
public void OnClick (dialoginterface dialog, int whichbutton) {
Dialog.dismiss ();
}
). Create ();
Dialog.show ();
}

Download the new version of the APK file, storage address can be placed in the SD card. Get the path in the SD card via Environment.getexternalstoragedirectory ()

The code is as follows Copy Code

private void Downfile (final String URL) {
Pbar.show ();
New Thread () {
public void Run () {
HttpClient client = new Defaulthttpclient ();
HttpGet get = new HttpGet (URL);
HttpResponse response;
try {
Response = Client.execute (get);
httpentity entity = response.getentity ();
Long length = Entity.getcontentlength ();
InputStream is = Entity.getcontent ();
FileOutputStream fileoutputstream = null;
if (is!= null) {
File F = new file (Update_dir);
if (!f.exists ()) {
F.mkdirs ();
}
FileOutputStream = new FileOutputStream (new File (Update_dir, updatefilename));

byte[] buf = new byte[1024];
int ch =-1;
int count = 0;
while (ch = is.read (buf))!=-1) {
Fileoutputstream.write (buf, 0, ch);
Count + = ch;
LOG.D (TAG, string.valueof (count));
if (length > 0) {
}
}
}
Fileoutputstream.flush ();
if (FileOutputStream!= null) {
Fileoutputstream.close ();
}

Handler.post (New Runnable () {
public void Run () {
Pbar.cancel ();
Installupdate ();
}
});
catch (Exception e) {
Pbar.cancel ();
LOG.E (TAG, E.getmessage ());
}
}

}.start ();
}

Install updates

The code is as follows Copy Code
private void Installupdate () {
Intent Intent = new Intent (Intent.action_view);
Intent.setdataandtype (Uri.fromfile, New File (Update_dir, Updatefilename)), "application/ Vnd.android.package-archive ");
Mcontext.startactivity (Intent);
}

This update requires a function to complete, according to their own business logic combined, the update function is done. can also be slightly encapsulated, written in a generic class, the next time you can use directly.

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.