Android: How to download file in android?

19,814

Solution 1

  1. You are doing network I/O on the main application thread. At best, this will freeze your UI while the download is going on. At worst, you activity will crash with an "Application Not Responding" (ANR) dialog.

  2. You are trying to write to a directory (download/) on external storage that might not exist. Please create the directory first.

  3. Please consider switching to using Log.e() for your error logging, as I do not know if printStackTrace() works on Android.

Also, make sure that you have the WRITE_EXTERNAL_STORAGE permission and that you are using adb logcat, DDMS, or the DDMS perspective in Eclipse to examine LogCat and look for the error messages you are trying to log.

Solution 2

the lib will be help you

https://github.com/AriaLyy/Aria

download file only one code

Aria.download(this)
    .load(DOWNLOAD_URL)
    .setDownloadPath(DOWNLOAD_PATH) //file save path
    .add();

get download state

@Download.onPre(DOWNLOAD_URL)
  protected void onPre(DownloadTask task) {}

  @Download.onTaskStart
  void taskStart(DownloadTask task) {}

  @Download.onTaskRunning
  protected void running(DownloadTask task) {}

  @Download.onTaskResume
  void taskResume(DownloadTask task) {}

  @Download.onTaskStop
  void taskStop(DownloadTask task) {}

  @Download.onTaskCancel
  void taskCancel(DownloadTask task) {}

  @Download.onTaskFail
  void taskFail(DownloadTask task) {}

  @Download.onTaskComplete
  void taskComplete(DownloadTask task) {}

  @Download.onNoSupportBreakPoint
  public void onNoSupportBreakPoint(DownloadTask task) {}

Solution 3

firstly, you should add permissions to AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>

Secondly, add this code, so that if the folder doesn't exist, it checks and creates the folder:

File root = android.os.Environment.getExternalStorageDirectory();               

           File dir = new File (root.getAbsolutePath() + "/download");
           if(!dir.exists()) {
                dir.mkdirs();
           }

Thirdly, as Commons Ware said, downloading on the main thread is not a good practice; you should implement it on a new thread; because while downloading, the main thread is busy for downloading the file. If the waiting time be more than expected the system will generate "Not responding" error.

In order to do that you can use "TaskAsync" or "IntentService" or even making a new thread.

As you said you are new to java, I suggest using "TaskAsync", as it is very straightforward and easy.

Share:
19,814
Kris
Author by

Kris

I love programming.

Updated on June 15, 2022

Comments

  • Kris
    Kris almost 2 years

    I'm trying to download a file from a URL. I have the following code.

    package com.example.downloadfile;
    
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.ProtocolException;
    import java.net.URL;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Environment;
    import android.util.Log;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class DownloadFile extends Activity {
    
         private static String fileName = "al.jpg";
    
         @Override
         public void onCreate(Bundle savedInstanceState) 
         {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            TextView tv = new TextView(this);
            tv.setText("This is download file program... ");
    
            try {
                //this is the file you want to download from the remote server
                String path ="http://www.fullissue.com/wp-content/uploads/2010/12/Adam-Lambert.jpg";
                //this is the name of the local file you will create
    
                String targetFileName = "al.jpg";
    
                boolean eof = false;
    
                URL u = new URL(path);
                HttpURLConnection c = (HttpURLConnection) u.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();
    
                String PATH_op = Environment.getExternalStorageDirectory() + "/download/" + targetFileName;
    
                tv.append("\nPath > " + PATH_op);
    
                FileOutputStream f = new FileOutputStream(new File(PATH_op));
    
                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();
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
    
            tv.append("\nAnother append!");
            this.setContentView(tv);
        }
    
    }
    

    Can someone tell me what's wrong with this code. I'm not able to see the file I'm supposed to download. I'm new to java and android dev, many thanks for any help. :)

  • Kris
    Kris almost 13 years
    Thanks for your response. 1. I just want to try downloading a file first. 2. download/ directory already exists. I also added WRITE_EXTERNAL_STORAGE permission on my AndroidManifest.xml 3. Is there other way to get the error, what I'm doing is, I copy the apk file then transfer and install it to my tablet.
  • Blundell
    Blundell almost 13 years
    You should hook your tablet up to eclipse with ADB that way you can get your stack traces in the DDMS perspective and deploy instantly with messing copying apk's