In the service by opening a thread in Oncreat (), rotation arraylist<attachmenttask> The task I downloaded for this attachment list,arraylist<attachmenttask> He maintains a task that is currently being downloaded, whenever one is downloaded and then added to the database after the download is complete.
/* * @project c6client * @package com.jh.c6.service * @file Downloadservice.java * @version 1.0 * @author LIAOYP * @time 2012-5-17 a.m. 2:55:19 */package com.jh.c6.service;import Java.io.file;import java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.net.URL;import Java.net.urlconnection;import Java.util.arraylist;import Java.util.list;import Android.app.Notification;import Android.app.notificationmanager;import Android.app.pendingintent;import Android.app.service;import Android.content.intent;import Android.os.handler;import Android.os.ibinder;import Android.widget.Toast;import Com.jh.c6.activity.c6clientactivity;import Com.jh.c6.activity.downloadmangeractivity;import Com.jh.c6.activity.R ; import Com.jh.c6.entity.attachmenttask;import Com.jh.c6.exception.poaexception;import Com.jh.c6.impl.DownloadDB; Import Com.jh.c6.util.configure;public class Downloadservice extends Service implements Runnable{private notificAtionmanager manager;private Notification notif;private Intent Intent; Handler Handler = new Handler () {public void Handlemessage (Android.os.Message msg) {if (msg.what = = 1) {Toast.maketext (Geta Pplicationcontext (), "The attachment has been downloaded", ". Show (); StartActivity ();} else if (msg.what = = 2) {startactivity (); Toast.maketext (Getapplicationcontext (), "The attachment is being downloaded", "." Show ();} else if (Msg.what = = 3) {//startactivity (); Toast.maketext (Getapplicationcontext (), "the attachment does not exist on the server!" ",". Show ();} Else{manager = (Notificationmanager) getsystemservice (Notification_service); Notification Notification = new Notification (r.drawable.ic_launcher, "Attachment Download", System.currenttimemillis ()); intent = new Intent (); Intent.setclass (Getapplicationcontext (), downloadmangeractivity.class); Intent.setflags (Intent.FLAG_ activity_clear_top| Intent.flag_activity_new_task); Pendingintent pendingintent = pendingintent.getactivity (Getapplicationcontext (), +, intent, pendingintent.flag_ update_current); Notification.setlatesteventinfo (Getapplicationcontext (), "Attachment download "," Download complete! ", pendingintent); Manager.notify (101, notification); Toast.maketext (Getapplicationcontext (), "Download Done", "$"). Show ();}};};/ /static linkedlist<attachmenttask> attstask = new linkedlist<attachmenttask> (); public static arraylist<attachmenttask> Attstask = new arraylist<attachmenttask> (); public void StartActivity () {intent = new intent (); Intent.setclass (Getapplicationcontext (), Downloadmangeractivity.class); Intent.setflags (intent.flag_activity_clear_top| Intent.flag_activity_new_task); DownloadService.this.startActivity (Intent); }public boolean isrun;public final static int Max = 4;public static Boolean stopdownload;static final Object No_more _work = new Object ();p rivate Thread t;private downloaddb downloaddb;private Intent download;private file file; @Overridepu Blic ibinder onbind (Intent Intent) {return null;} /** * Maximum limit * @return */public static Boolean ismaxnum () {return attstask.size () >=max? True:false;} /** * The Task List has a task * @param path * @reTurn */public Static Boolean isdownloading (String path) {for (int i = 0; i < attstask.size (); i++) {if (Attstask.get (i). GetURI (). Equals (path) {return true;}} return false;} /** * * <code>getTask</code> * @description: TODO (get total attachments) * @return * @since 2012-4-18 liaoyp */public static int Gettask () {if (Uploadservice.attstask!=null) return attstask.size (); else return 0;} /** * Download Complete! * @return */public static Boolean isdowloadfinshed () {for (int i = 0; i < attstask.size (); i++) {if (!attstask.get (i) . Isover ()) {return false;}} return true;} /** * Server address * @return */public static list<string> Getdownloadserverpath () {list<string> Atts = null;if (attsTa SK!=null && attstask.size () >0) {Atts = new arraylist<string> (); for (int i = 0; i < attstask.size (); I + +) {if (Attstask.get (i). Isover ()) {Atts.add (Attstask.get (i). Getserverpath ());}} return atts;} return atts;} @Overridepublic void OnCreate () {super.oncreate (); isrun= true; t = new Thread (this); T.STart ();} @Overridepublic void OnStart (Intent Intent, int startid) {//TODO auto-generated method Stubsuper.onstart (Intent, Startid if (Intent!=null &&intent.getextras ()!=null) {if (t = = null) {t = new Thread (this); T.start ();} String uri = (string) Intent.getextras (). Get ("uri"), if (Uri!=null) {for (int i = Attstask.size ()-1; I >= 0; i--) {if (a Ttstask.get (i). GetURI (). Equals (URI)) {stopdownload = True;attstask.remove (i); System.out.println ("cancle---->" +attstask.size ()) This.sendbroadcast (New Intent ( c6clientactivity.updatedowload));}}}} @Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {return Super.onstartcommand (Intent, Flags, STA Rtid);} @Overridepublic void Run () {while (Isrun) {try {if (attstask.size () > 0) {for (int i = 0; I <attstask.size (); i++) {at Tachmenttask task = Attstask.get (i), if (! Task.isunsart ()) {Download (Attstask.get (i));}}} else {try {Thread.Sleep],} catch (Exception e) {}}}catch (Exception e) {System.out.println ("error-----------------"+e);}}} private void Download (Attachmenttask Task) throws Poaexception {//TODO auto-generated method stub//start uploading and updating the download progress display Syste M.out.println ("Dowenload-----------------1"); Task.setunsart (true); task.setsarting (true); if (downloaddb = = null) { DOWNLOADDB = new Downloaddb ();} String httppath; httppath = Task.geturi (); String Loacalpath = Downloaddb.getlocalpicpath (Downloadservice.this, Httppath); System.out.println ("LocalPath:" +loacalpath); if (Loacalpath = = null) {Boolean b = isdownloading (Httppath); if (b) {//Send broadcast Notification removetask (Task); Handler.sendemptymessage (2); }else{//download startdowload (Task); }//Toast.maketext (Getapplicationcontext (), "Start Download", "page"). Show (); Startdowload (Task); }else{File File = new file (Loacalpath); if (! file.exists ()) {//download startdowload (Task); }else{//Jump to Attachment Management interface Removetask (Task); Handler.sendemptymessage (1); }}}public void Startdowload (Attachmenttask task) {INPUtstream is = null; FileOutputStream fos = null; String Httppath = ""; try {Httppath = (Configure.IPADDRESS.replaceAll ("Postserviceforandroid.svc", "") + " Fileoutsteam.aspx? Fileid= "+task.geturi ()); System.out.println ("http:" +httppath); URLConnection connetion = new URL (Httppath). OpenConnection (); Is=connetion.getinputstream ();//httpget httpget = new HttpGet (Task.geturi ());//httpclient client = new Defaulthttpclient ();//httpparams httpparams = Client.getparams ();//httpconnectionparams.setconnectiontimeout ( httpparams,5000);//httpconnectionparams.setsotimeout (Httpparams, 10000);//httpresponse HttpResponse = Client.execute (HttpGet);//if (Httpresponse.getstatusline (). Getstatuscode () = = () {////is = httpresponse.getentity ( ). GetContent ();//Start download apk file String path = Configure.datadir+configure.downloadfile + "/" +task.getserverpath (); File = new file (path); if (! file.exists ()) {file.createnewfile (); FOS = new FileOutputStream (file); byte[] buffer = new Byte[2048];int count = 0;while ((count = Is.read (buffer))! =-1) {if (stopdownload) {break;} Fos.write (buffer, 0, count);//progress with new long current= task.getcurrentprogress (); current =task.getcurrentprogress () + Count;task.setcurrentprogress (current);//send broadcast to Mangeattachmengactivitydownload = new Intent ( c6clientactivity.dowloadaction);d Ownload.putextra ("type", 0); this.sendbroadcast (download); System.out.println ("Download ..."); Fos.flush (); Removetask (Task); if (downloaddb! = null) {downloaddb.insertpic (Downloadservice.this, Task.geturi (), Path , Configure.accountid);} Else{new downloaddb (). Insertpic (Downloadservice.this, Task.geturi (), Path, Configure.accountid);} Prompt Download complete! download = new Intent (c6clientactivity.dowloadaction);//download.putextra ("type", 1);//this.sendbroadcast ( download); handler.sendemptymessage (0);} catch (FileNotFoundException e) {e.printstacktrace (); Handler.sendemptymessage (3);} catch (IOException e) {e.printstacktrace ();} finally{try {if (fos! = null) {Fos.close ();}} catch (IOException e) {e.prints TacktRace ();} try {if (is! = null) {Is.close ()}} catch (IOException e) {e.printstacktrace ();}}} public static void Removetask (Attachmenttask Task) {if (Attstask.contains (Task)) {Attstask.remove (Task);}} public static void AddTask (Attachmenttask task) {stopdownload = False;attstask.add (Task);} @Overridepublic void OnDestroy () {Super.ondestroy (); isrun = false;}}
Android Background Accessory Download