First, infer whether there is SDcard card
Infer if there is an SD card//ture: There is an SD card//false: No SD card public boolean Avaiablemedia () { String status= Environment.getexternalstoragestate (); if (Status.equals (environment.media_mounted)) { return true; } else { return false;} }
Second, download the file to SDcard card
if (Avaiablemedia ()) {HttpClient client = new Defaulthttpclient (); HttpGet get = new HttpGet (URL); HttpResponse response; try {response = Client.execute (get); httpentity entity = response.getentity (); Long length = Entity.getcontentlength (); InputStream is = Entity.getcontent (); FileOutputStream fileoutputstream = null; if (is = null) {File File = new file (Environment.getexternalstoragedirectory (), "test.apk"); FileOutputStream = new FileOutputStream (file); byte[] buf = new byte[1024]; int ch =-1; int count = 0; while (ch = is.read (BUF))! =-1) {fileoutputstream.write (buf, 0, ch); Count + = ch; }} fileoutputstream.flush (); if (FileOutputStream! = null) {fileoutputstream.close (); } if (is = null) {is.close (); } } catch (Clientprotocolexception e) {e.printstacktrace (); } catch (IOException e) {e.printstacktrace (); }}
Iii. downloading files to the data directory of this application
else{try {fileoutputstream outstream = this.openfileoutput ("test.apk", context.mode_world_readable); HttpClient client = new Defaulthttpclient (); HttpGet get = new HttpGet (URL); HttpResponse response; Response = Client.execute (get); httpentity entity = response.getentity (); Long length = Entity.getcontentlength (); InputStream is = Entity.getcontent (); int count = 0; if (is! = null) {byte[] buf = new byte[1024]; int ch =-1; while (ch = is.read (buf)) >0) {outstream.write (buf,0,ch); Count + = ch; Toast.maketext (Getapplicationcontext (), "Downloading upgrade package ...", Toast.length_short). Show (); }} outstream.flush (); if (OutStream! = null) {outstream.close (); } if (is = null) {is.close (); }} catch (ClientprotocolexceptiOn e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}}