Since the service runs in the background, once run, use toast notifications and Status Bar Notification
To inform the customer.
Service-combined notification and user interaction:
Public classDownloadserviceextendsService {PrivateString URI; //Notification Manager PrivateNotificationmanager Nmanager; PrivateNotification.builder Builder; @Override Public voidonCreate () {Super. OnCreate (); GetNotification (); } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {URI= Intent.getstringextra ("uri"); //start the download process NewThread (Newmyrunnable ()). Start (); returnStart_sticky; } /*** Download and execute in thread, **/ Public classMyrunnableImplementsRunnable {@Override Public voidrun () {//data stored for reading byte[] result =NULL; HttpClient Client=Newdefaulthttpclient (); Try{log.i ("Tag", "uri>>" +URI); HttpGet Get=NewHttpGet (URI); HttpResponse Response=Client.execute (GET); Httpentity Entity=response.getentity (); intStatecode =response.getstatusline (). Getstatuscode (); if(Statecode! = 200) {log.i ("Tag", statecode+ "-Download failed--"); } //get the network input streamInputStream in =entity.getcontent (); //get total network data length LongTotal =entity.getcontentlength (); byte[] bs =New byte[10]; intLen_per = 0;//the length of each read,Bytearrayoutputstream BAOs =NewBytearrayoutputstream (); intReadedlen = 0;//The amount of data that has been read while((Len_per = In.read (BS))! =-1) {baos.write (BS,0, Len_per); Readedlen+=Len_per;
//Send progress message to handler, update progress in handler int progress = (int) ((readedlen*100)/(float) total); Message msg = Message.obtain (); MSG.ARG1 = Progress; Handler.sendmessage (msg); } result=Baos.tobytearray ();
//Notification completed Handler.sendemptymessage (1); }Catch(Exception e) {e.printstacktrace (); }finally { if(Client! =NULL) {Client.getconnectionmanager (). Shutdown (); } }} @Override Publicibinder onbind (Intent Intent) {return NULL; } /*** Update UI*/ PrivateHandler Handler =NewHandler () { Public voidhandlemessage (Message msg) {//Update UIBuilder.setprogress (MSG.ARG1,false); Nmanager.notify (1001, Builder.build ()); if(Msg.what = = 1){ //Download CompleteToast.make (Getapplicationcontext (), "Download Done", 1). Show (); s}} }; /*** Notification Initialization*/ Private voidgetnotification () {Nmanager=(Notificationmanager) Getsystemservice (Context.notification_service); Builder=NewNotification.builder (Getapplicationcontext ()); Builder.setsmallicon (R.drawable.ic_launcher); Builder.setticker ("The notice is coming."); Builder.setcontenttitle (Download); Builder.setcontenttext ("Downloading ....." "); }}
Android Four component service (7) combined notification