Android Service Background Download

Source: Internet
Author: User

 Service

ImportAndroid.app.NotificationManager;ImportAndroid.app.Service;ImportAndroid.content.Context;Importandroid.content.Intent;ImportAndroid.net.Uri;ImportAndroid.os.AsyncTask;Importandroid.os.Environment;ImportAndroid.os.IBinder;ImportAndroid.support.v7.app.NotificationCompat;ImportAndroid.util.Log;ImportAndroid.widget.Toast;ImportJava.io.File;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.net.URL;Importjava.net.URLConnection;/*** Created by DK on 2016/11/25.*/ Public classDownloadsignatureserviceextendsService {protected Static FinalString Filerootpath = environment.getexternalstoragedirectory () +File.separator; protected Static FinalString Filedownloadpath = "sunrise/download/"; protected intFileszie;//File Size protected intFilecache;//File Cache protectedString fileName = "";//file name protectedString filenametemp = "";//Temporary Files protectedString urlstr = "";//Download URL protectedFile Downloaddir, DownloadFile, downloadfiletemp; protected StaticNotificationmanager Mnotifymanager; protected StaticNotificationcompat.builder Mbuilder; protected Static Final intNOTIFIID = 0x000; protected Static FinalString TAG = "LLL::"; @Override Publicibinder onbind (Intent Intent) {return NULL; } @Override Public voidonCreate () {Super. OnCreate (); } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {LOG.E (TAG,"Onstartcommand"); Urlstr= (String) Intent.getextras (). Get ("Signatureurl"); LOG.E (TAG,"URLSTR =" +urlstr); /*Signature Download Url*/DownloadFile (URLSTR); return Super. Onstartcommand (Intent, flags, Startid); } @Override Public voidOnDestroy () {LOG.E (TAG,"OnDestroy"); Super. OnDestroy (); } /*** Download Signature * *@paramDownloadURL*/ protected voidDownloadFile (String downloadurl) {log.e (TAG,"DownloadFile"); /*file name*/FileName= Downloadurl.substring (Downloadurl.lastindexof ("/") + 1); /*Cache Files*/filenametemp= "Download.tmp"; /*Download Catalogue*/Downloaddir=NewFile (Filerootpath +Filedownloadpath); DownloadFile=NewFile (Filerootpath + Filedownloadpath +fileName); Downloadfiletemp=NewFile (Filerootpath + Filedownloadpath +filenametemp); if(!downloaddir.exists ()) {Downloaddir.mkdirs (); } /*How files exist for this installation file*/ if(Downloadfile.exists ()) {Installapp (downloadsignatureservice). This, Filerootpath + Filedownloadpath +fileName); } /*otherwise download the file*/ Else{Mnotifymanager=(Notificationmanager) downloadsignatureservice. This. Getsystemservice (Downloadsignatureservice. This. Notification_service); Mbuilder=NewNotificationcompat.builder (Downloadsignatureservice. This); Mbuilder.setcontenttitle ("Download e-signature App"). Setcontenttext ("Downloading ..."). Setprogress (100, 0,false). Setsmallicon (Android. R.drawable.stat_sys_download); //DownloadFile NewAsynctask<string, Integer, string>() {@Overrideprotected voidOnPreExecute () {Mbuilder.setticker ("Download electronic signature"). Setprogress (100, 0,false); Mnotifymanager.notify (Notifiid, Mbuilder.build ()); Super. OnPreExecute (); } @Overrideprotected voidonprogressupdate (Integer ... values) {LOG.E (TAG,"---download cache" + values[0] + "---"); intpp = ((values[0] + 1) * 100/Fileszie); Mbuilder.setprogress (P, pp,false). Setcontenttext ("downloaded" + pp + "%"); Mnotifymanager.notify (Notifiid, Mbuilder.build ()); Super. Onprogressupdate (values); } @Overrideprotectedstring Doinbackground (String ... params) {Try{fileName= Params[0].substring (Params[0].lastindexof ("/") + 1); LOG.E ("LLL", "---fileName =" +fileName); //Get file nameURL Myurl =NewURL (params[0]); URLConnection Conn=myurl.openconnection (); Conn.setdoinput (true); Conn.connect (); InputStream is=Conn.getinputstream (); Fileszie= Conn.getcontentlength ();//get file size based on response if(Fileszie <= 0) { Throw NewRuntimeException ("Unable to learn file size"); } if(IS = =NULL)Throw NewRuntimeException ("Stream is null"); /*Download Catalogue*/ if(!downloaddir.exists ()) {Downloaddir.mkdirs (); } //storing data in Path + file nameFileOutputStream fos =NewFileOutputStream (downloadfiletemp); byteBuf[] =New byte[1024]; Filecache= 0; Do { //Loop Read intNumread =Is.read (BUF); if(Numread = =-1) { Break; } fos.write (BUF,0, Numread); Filecache+=Numread; This. publishprogress (Filecache); } while(true); Try{is.close (); } Catch(Exception ex) {LOG.E ("Tag", "Error:" +ex.getmessage ()); } } Catch(IOException e) {e.printstacktrace (); } return"Download Succeeded"; } @Overrideprotected voidOnPostExecute (String s) {/*after the download is successful*/ if(Downloadfiletemp.exists ()) {Downloadfiletemp.renameto (downloadfile); } toast.maketext (Downloadsignatureservice. This, S, Toast.length_short). Show (); /*Cancel Notification*/Mbuilder.setcontenttext (s). Setprogress (100, 0,false); Mnotifymanager.cancel (NOTIFIID); Installapp (Downloadsignatureservice. This, Filerootpath + Filedownloadpath +fileName); /*Service Kill Suicide*/Downloadsignatureservice. This. Stopself (); Super. OnPostExecute (s); }}.execute (DownloadURL); } } /*** Install APK * *@paramContext *@paramFilePath*/ Public voidInstallapp (Context context, String FilePath) {File _file=NewFile (FilePath); Intent Intent=NewIntent (Intent.action_view); Intent.setflags (Intent.flag_activity_new_task); Intent.setdataandtype (Uri.fromfile (_file),"Application/vnd.android.package-archive"); Context.startactivity (Intent); }}

Start the service
New Bundle (); Bundle.putstring ("Signatureurl", Instance.signatureurl "the address you downloaded"); /* Electronic signature */  New Intent (). SetClass (CTX, Downloadsignatureservice.  Class). Putextras (bundle); StartService (it);

Permissions
<!--permission to read and write memory cards--    <uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>    <!--access to networking rights--    <uses-permission android:name= "Android.permission.INTERNET"/>

Configuration

<service android:name= ". Service.downloadsignatureservice "/>

  

This is already very easy to understand, you can refer to the download after the completion of automatic installation, and so on, need to see,
Asynctask<string, Integer, string>

Android Service Background Download

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.