Android update notification bar with progress bar

Source: Internet
Author: User

On the Internet to check the next. Android version number update notification bar with progress bar, drunk, basically is copied over. Some of the code is not complete, even the source code download is not. There is also need to download points, not to use, really black heart Ah!! Before I also wrote their own definition of the notification bar Notification, think or write it yourself.

Due to the update in the notification bar, you need to visit the network download. A service was written and a download update was implemented in the service.

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 (); }/** * Initializes global variables * This method is serverversion from the server side in the actual work. It is best to run the activity in the splash screen */public void Initglobal () {try{global.localversion = Getpackagemanager (). g Etpackageinfo (Getpackagename (), 0). Versioncode; Set the local version number Global.serverversion = 2;//Assume that the server version number is 2.        The local version number defaults to 1}catch (Exception ex) {ex.printstacktrace (); }}/** * Check the update version number */public void checkversion () {if (Global.localversion < Global.serverver sion) {//Discover new version number, prompt user to update alertdialog.            Builder alert = new Alertdialog.builder (this);                 Alert.settitle ("Software Upgrade"). Setmessage ("Discover the new version number, we recommend updating it immediately.") . Setpositivebutton ("Update", new Dialoginterface.onclicklistener () {public void OnClick (Dialoginterface D Ialog, int which) {//Open update Service Updateservice//This is to make the update more modular and capable of transmitting 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 number 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 is the value that the notification hint flashes. notification.tickertext = "Start download";// Pendingintent = pendingintent.getactivity (this, 0, updateintent, 0);// The number of references in this 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 "); ##.00%//percent format. The back is 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 number update get SD card installation package path =" + File.geta Bsolutepath ()); 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 {//* assumes that it cannot be opened directly. Just jump out of the software list to the user select */type = "*/*";} return type;}}

Basically the gaze is written clearly, which uses the Xutils Open source framework to download files.

If you think you can see the trouble directly click Download Demo bar. No points required.

。。


Android update notification bar with progress bar

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.