How to download a file after clicking a button (Android Studio) -
i created activity in app. wanted user download .pdf file when he/she wants view guidelines. wanted implement on button. idea how properly?
heres code below:
public class exhibitor_registration_activity extends appcompatactivity { button buttondownload; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_exhibitor_registration_); this.settitle("buyer registration"); toolbar mytoolbar = (toolbar) findviewbyid(r.id.my_toolbar); setsupportactionbar(mytoolbar); getsupportactionbar().setdisplayhomeasupenabled(true); mytoolbar.setnavigationicon(r.drawable.ic_arrow_back_white_24dp); final button buttondownload = (button) findviewbyid(r.id.buttondownload); buttondownload.setonclicklistener(new view.onclicklistener(){ @override public void onclick(view view) { try { //this file want download remote server string path ="http://www.manilafame.com/website-assets/downloads/exhibitor-application-kit/local/201704/1-summary-of-participation-details-april-2017_mn_002.pdfp"; //this name of local file create string targetfilename = null; boolean eof = false; url u = new url(path); httpurlconnection c = (httpurlconnection) u.openconnection(); c.setrequestmethod("get"); c.setdooutput(true); c.connect(); fileoutputstream f = new fileoutputstream(new file("c:\\junk\\"+targetfilename)); inputstream in = c.getinputstream(); byte[] buffer = new byte[1024]; int len1 = 0; while ( (len1 = in.read(buffer)) > 0 ) { f.write(buffer,0, len1); } f.close(); } catch (malformedurlexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (protocolexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (filenotfoundexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } }); } }
if want resumable, speed of download ... follow steps
create class downloadmanager.java
public class downloadmanager extends asynctask<string,string,string>{ string downloadlink,filedestination; public static final int on_init=100,on_error=102,on_prograss=103,on_completed=104,status_downloaded=1500,status_not_yet=1501; private onupdatelistener onupdatelistener; private string downloadedpath=""; private long downloaded=0; private file file; private string returndata=null; private file cachedownloadfile; public downloadmanager(string downloadlink,string filedestinationpath){ this.downloadlink=downloadlink; this.filedestination=filedestinationpath; file=new file(filedestination, tools.getfilename(downloadlink)); cachedownloadfile=new file(appcostants.chache_path+tools.getfilename(downloadlink)); try { if(cachedownloadfile.isfile()) downloaded=tools.getfilesize(cachedownloadfile); else downloaded=0; log.d("file_download_tag_p",downloaded+" <- "+cachedownloadfile.getabsolutepath()); } catch (ioexception e) { e.printstacktrace(); } fireonupdate(on_init,"init ..."); } @override protected string doinbackground(string... params) { try { file dir=new file(filedestination); file chachedir=new file(appcostants.chache_path); if(!chachedir.isdirectory()) chachedir.mkdirs(); if(!dir.isdirectory()){ dir.mkdirs(); } if(file.exists()) { log.d("file_download_tag","file exist return complete"); return "completed";//file exist } if(!cachedownloadfile.exists()){ cachedownloadfile.createnewfile(); } log.d("file_download_tag","link "+downloadlink); url url=new url(downloadlink); httpurlconnection urlconnection= (httpurlconnection) url.openconnection(); if(downloaded>0) urlconnection.setrequestproperty("range","byte="+downloaded); urlconnection.connect(); int status = urlconnection.getresponsecode(); inputstream inputstream=urlconnection.getinputstream(); int totalsize=urlconnection.getcontentlength(); if(totalsize<=downloaded){ returndata= "completed"; publishprogress("file checked "+tools.getfilename(file.getabsolutepath())); return returndata; } this.downloadedpath=cachedownloadfile.getabsolutepath(); byte[] buffer=new byte[1024]; int bufferlength=0; fileoutputstream fileoutput=new fileoutputstream(cachedownloadfile); long d=0; long starttime=system.currenttimemillis(); while ((bufferlength=inputstream.read(buffer))>0){ fileoutput.write(buffer,0,bufferlength); downloaded+=bufferlength; d+=bufferlength; //string l=" "+tools.getfilename(file.getabsolutepath())+" ( "+tools.convertmemory(downloaded)+" / "+tools.convertmemory(totalsize)+" )"; string l=" "+tools.convertmemory(downloaded)+" / "+tools.convertmemory(totalsize)+" ( "+getdownloadspeed(starttime,d)+" )"; publishprogress(l); if(downloaded>=totalsize){ break; } } log.d("file_download_tag","dwonloaded "+downloadedpath+" ("+cachedownloadfile.length()+")"); fileoutput.close(); if(tools.filecopy(file,cachedownloadfile)){ log.d("file_download_tag","file copied, delete cache"); cachedownloadfile.delete(); } returndata="completed"; } catch (malformedurlexception e) { returndata=null; e.printstacktrace(); publishprogress(e.tostring()); log.d("###################",e+""); } catch (ioexception e) { returndata=null; e.printstacktrace(); publishprogress(e.tostring()); } return returndata; } @override protected void onprogressupdate(string... values) { super.onprogressupdate(values); fireonupdate(on_prograss,values[0]); } @override protected void onpostexecute(string s) { super.onpostexecute(s); if(s!=null){ fireonupdate(on_completed,downloadedpath); }else{ fireonupdate(on_error,"download failed"); } } public interface onupdatelistener{ void onupdate(int code,string message); } public void setonupdatelistener(onupdatelistener onupdatelistener){ this.onupdatelistener=onupdatelistener; } private void fireonupdate(int code,string message){ if(onupdatelistener!=null) onupdatelistener.onupdate(code,message); } private string getdownloadspeed(long starttime,float totaldownloaded) { long elapsedtime = system.currenttimemillis() - starttime; //byte : float speed=1000f * totaldownloaded / elapsedtime; return convert(speed); } private string convert(float value){ long kb=1024 ,mb=kb*1024 ,gb=mb*1024; if(value<kb){ string speed=(value+""); speed=speed.substring(0,speed.indexof('.')+2); return speed+" b/s"; }else if(value<mb){ value=value/kb; string speed=(value+""); speed=speed.substring(0,speed.indexof('.')); return (speed)+" kb/s"; }else if(value<gb){ value=(value/mb); string speed=(value+""); speed=speed.substring(0,speed.indexof('.')); return speed+" mb/s"; } return ""; } }
use code in onclick() downloadmanager downloadmanager = new downloadmanager(url,filepath);
set event
downloadmanager.setonupdatelistener(new downloadmanager.onupdatelistener() { @override public void onupdate(int code, string message) { if (code == downloadmanager.on_completed) { } if(downloadmanager.on_prograss==code){} } });
start download
downloadmanager.execute();
lib setup
compile "commons-io:commons-io:+"
tools.java
public static long getfilesize(file file) throws ioexception { fileoutputstream fileoutputstream=new fileoutputstream(file); fileoutputstream.close(); return file.length(); } public static boolean filecopy(file dest,file source){ try { fileutils.copyfile(source,dest); return true; } catch (ioexception e) { e.printstacktrace(); return false; } }
Comments
Post a Comment