In the online query, Android version update notification bar with progress bar, drunk, basic is copied over, some code is not complete, even the source download is not, there is also need to download points, not use, really black heart Ah!! I also wrote a custom notification bar Notification, think or write it yourself.
Because in the notification bar update, need to access the network download, wrote a service, in the service to achieve the download update.
First look at the Mainactivity code:
Package Com.wsj.wsjdemo;import Android.os.bundle;import Android.app.activity;import android.app.alertdialog;import Android.content.dialoginterface;import Android.content.intent;import Android.view.menu;public class MainActivity Extends Activity {@Override protected void onCreate (Bundle savedinstancestate) {super.oncreate (Savedinstanc EState); Setcontentview (R.layout.activity_main); Initglobal (); Checkversion (); }/** * Initialize global variables * In practice this method serverversion from the server side, preferably in the activity of the splash screen execute */public void Initglobal () { try{global.localversion = Getpackagemanager (). Getpackageinfo (Getpackagename (), 0). Versioncode;//Set local version number Global.serverversion = 2;//assumes the server version is 2, the local version defaults to 1}catch (Exception ex) {ex.printstacktrace (); }}/** * Check for updated version */public void checkversion () {if (Global.localversion < Global.serverver sion) {//Discover new version, prompt user to update Alertdialog.builDer Alert = new Alertdialog.builder (this); Alert.settitle ("Software Upgrade"). Setmessage ("New version found, recommended for immediate update use.") . Setpositivebutton ("Update", new Dialoginterface.onclicklistener () {public void OnClick (Dialoginterface D Ialog, int which) {//Open update Service Updateservice//here in order to better modularize the update, you can pass some Updatese Rvice dependent values//such as layout ID, resource ID, dynamically obtained caption, here take App_name for example Intent updateintent =new Inte NT (Mainactivity.this, Updateservice.class); Updateintent.putextra ("App_name", r.string.app_name); Updateintent.putextra ("Downurl", "http://www.subangloan.com/Contract/App/Android/caijia_unsign_signed.apk"); StartService (updateintent); }}). Setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {PU Blic void OnClick (Dialoginterface dialog, int wHich) {Dialog.dismiss (); } }); Alert.create (). Show (); }else{//cleanup work, omit//cheanupdatefile (), I will append the code after the article}}}
Activity_main.xml file: Nothing there is a simple interface
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools " android:layout_width=" match_parent " android:layout_height=" Match_parent " > <textview android:layout_width= "wrap_content" android:layout_height= "Wrap_content " android:text= "@string/hello_world"/></linearlayout>
The Global.java used in main
Package Com.wsj.wsjdemo;public class Global {//version information public static int localversion = 0; public static int serverversion = 0; public static String Downloaddir = "app/download/";}
Write the service implementation Updateservice.java
Package Com.wsj.wsjdemo;import Java.io.file;import Java.io.ioexception;import java.text.decimalformat;import Com.lidroid.xutils.httputils;import Com.lidroid.xutils.exception.httpexception;import Com.lidroid.xutils.http.responseinfo;import Com.lidroid.xutils.http.callback.requestcallback;import Android.app.notification;import Android.app.notificationmanager;import Android.app.pendingintent;import Android.app.service;import Android.content.context;import Android.content.intent;import Android.net.Uri;import Android.os.handler;import Android.os.ibinder;import Android.os.message;import Android.widget.RemoteViews;public Class Updateservice extends Service {private static String down_url;//= "http://192.168.1.112:8080/360.apk";p rivate STA Tic Final int down_ok = 1; Download complete private static final int down_error = 0;private String app_name;private notificationmanager NOTIFICATIONMANAGER;PR Ivate Notification notification;private Intent updateintent;private pendingintent pendingintent;private StrinG updatefile;private int notification_id = 0;long totalsize = 0;//file Total size/*** * Update UI */final Handler Handler = new Handler ( {@SuppressWarnings ("deprecation") @Overridepublic void Handlemessage (Message msg) {switch (msg.what) {case down_ok:// Download complete, click install intent installapkintent = getfileintent (new File (updatefile));p endingintent = pendingintent.getactivity ( Updateservice.this, 0, installapkintent, 0); notification.contentintent = Pendingintent;notification.flags |= Notification.flag_auto_cancel;notification.setlatesteventinfo (Updateservice.this, App_name, "Download successful, click Install", pendingintent); notificationmanager.notify (notification_id, notification); StopService (updateintent); break;case DOWN_ERROR:notification.setLatestEventInfo (Updateservice.this, app_name, "Download Failed", pendingintent); Break;default: StopService (updateintent); break;}}; @Overridepublic ibinder onbind (Intent arg0) {return null;} @Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {if (Intent! = null) {try {app_name = Intent. Getstringextra ("App_name");d Own_url = Intent.getstringextra ("Downurl");//create File Updatefile = Fileutils.getdiskcachedir (Getapplicationcontext (), "xxxx.apk"), if (!updatefile.exists ()) {try { Updatefile.createnewfile ();} catch (IOException e) {e.printstacktrace ();}} Create notification createnotification ();//Start Download downloadupdatefile (Down_url, Updatefile.getabsolutepath ());} catch (Exception e) {e.printstacktrace ();}} Return Super.onstartcommand (Intent, flags, Startid);} /*** * Create notification bar */remoteviews Contentview, @SuppressWarnings ("deprecation") public void Createnotification () { Notificationmanager = (Notificationmanager) getsystemservice (context.notification_service); NOTIFICATION = new Notification (); Notification.icon = r.drawable.ic_launcher;//This parameter is the value that the notification prompt flashes out. notification.tickertext = "Start download";// Pendingintent = pendingintent.getactivity (this, 0, updateintent, 0);// This parameter is the notification bar view display content Notification.setlatesteventinfo (this, app_name, "Download: 0%", pendingintent);// Notificationmanager.notify (notification_id, Notification);/*** * Here we use a custom view to display notification */contentview = new Remoteviews (Getpackagename (), R.layout.notification_ Item); Contentview.settextviewtext (R.id.notificationtitle, "downloading"); Contentview.settextviewtext ( R.id.notificationpercent, "0%"); Contentview.setprogressbar (r.id.notificationprogress, 0, false); Notification.contentview = Contentview;updateintent = new Intent (this, mainactivity.class); Updateintent.addflags ( Intent.flag_activity_single_top);p endingintent = pendingintent.getactivity (this, 0, updateintent, 0); Notification.contentintent = pendingintent;notificationmanager.notify (notification_id, notification);} /*** * Download file */public void Downloadupdatefile (String down_url, String file) throws Exception {updatefile = file; Httputils httputils = new Httputils (); Httputils.download (Down_url, file, new requestcallback<file> () {@Overridepublic void onsuccess (responseinfo <File> responseinfo) {//download successful Message message = Handler.obtainmessage (); message.what = Down_ok;handler.sendmessage (message); installapk (new File (Updatefile), updateservice.this);} @Overridepublic void OnFailure (httpexception error, String msg) {Message message = Handler.obtainmessage (); message.what = down_error;handler.sendmessage (message);} @Overridepublic void onloading (Long, Long, Boolean isuploading) {super.onloading (total, Current, isuploading);d ouble x_double = current * 1.0;double Tempresult = X_double/total;decimalformat df1 = new DecimalFormat ("0 .00 "); The ##.00%//percent format, followed by less than 2 bits, with 0 padded string result = Df1.format (Tempresult); Contentview.settextviewtext ( R.id.notificationpercent, (int) (Float.parsefloat (Result) * +) + "%"); Contentview.setprogressbar ( R.id.notificationprogress, +, (int) (Float.parsefloat (Result) *), false); Notificationmanager.notify ( NOTIFICATION_ID, notification);});} After the download is complete, open the install APK interface public static void installapk (file file, context context) {//l.i ("msg", "version update get the path of the SD card installation package =" + File.getab Solutepath ()); Intent openFile = getfileintent (file); Context.startacTivity (openFile);} public static Intent getfileintent (file file) {uri uri = uri.fromfile (file); String type = getmimetype (file), Intent Intent = new Intent ("Android.intent.action.VIEW"); Intent.addcategory (" Android.intent.category.DEFAULT "); Intent.addflags (Intent.flag_activity_new_task); Intent.setdataandtype (URI, type); return intent;} public static string GetMimeType (File f) {String type = ""; String fName = F.getname ();//Gets the extension string end = Fname.substring (Fname.lastindexof (".") + 1, fname.length ()); if (end.equal S ("apk")) {type = "application/vnd.android.package-archive";} else {//* If it cannot be opened directly, jump out of the software list to the user to choose */type = "*/*";} return type;}}
Basically the notes are written clearly, which uses the Xutils Open source framework to download the files.
If you feel the trouble to see directly download the demo bar, do not need points. Feel good, hope in the article at the bottom to give a review, which is also for me to set, thank you
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android update notification bar with progress bar