1

In an android app, I am trying to download a file from a web server to /Download folder on external storage. download code is executed in a HandlerThread in a service.

The service is doing other functions apart from downloading file. the code for downloading goes like this:

public void downloadFile(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    URL url = new URL("http://192.168.1.105/download/apkFile.apk");
                    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                    InputStream inputStream = connection.getInputStream();

                    File file = new File(Environment.getExternalStorageDirectory().getPath()+"/Download/apkFile.apk");
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    int bytesRead;
                    byte[] buffer = new byte[4096];
                    while((bytesRead = inputStream.read(buffer)) != -1){
                        fileOutputStream.write( buffer, 0, bytesRead);
                    }
                    fileOutputStream.close();
                    inputStream.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

There is no error in executing but the file is not downloaded. Please suggest.

anant sophia
  • 55
  • 2
  • 12
  • So which directory the file is stored in ? – ThaiPD May 07 '15 at 16:34
  • What does showOutput tell you now? Put a showOutput in the catch block too. Is there connection? Put log ststements in your code so you can follow the flow. – greenapps May 07 '15 at 18:06
  • @greenapps you are right to point out, it doesn't really mean anything ...I've edited the code. Any suggestions why the file doesn't download.. – anant sophia May 07 '15 at 18:14
  • Man do not remove it but use it to check what happens. Now did it display the url? Because if it did all your code was executed. So put it back in. And also one in the catch block. Then add a lot of Log.d() statements. Let us see how you updated the code and tell us what all happened. – greenapps May 07 '15 at 18:20
  • @PhanDinhThai the file will be stored in /Download directory.. – anant sophia May 07 '15 at 18:20
  • @greenapps, yes the showOutput(url) was giving desired url, I has also checked it in debugger .... control does not enter the catch block! – anant sophia May 07 '15 at 18:23
  • Also log in that loop bytesRead. And count totalBytesRead. Log them. How do you check that the file exists on your device? You are not using the Download app for that do you? – greenapps May 07 '15 at 18:28
  • @greenapps I'm a newbie, following you is rather difficult. I've tried stepping in through debugger, i could see that the connection did get = true, but could not make full meaning....however control never went to catch block. – anant sophia May 07 '15 at 18:44
  • Even if you are a newbie you could answer my question concerning how you checked the file was not there. – greenapps May 07 '15 at 21:23
  • By going to the directory using other UI based app(File Commander) and not finding it. – anant sophia May 08 '15 at 00:32

2 Answers2

4

You can use AndroidDownloadManager.

This Class handles all the steps of the download of a file and gets you information about the progress ext...

You should avoid the use of threads.

This is how you use it:

public void StartNewDownload(url) {       
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); /*init a request*/
    request.setDescription("My description"); //this description apears inthe android notification 
    request.setTitle("My Title");//this description apears inthe android notification 
    request.setDestinationInExternalFilesDir(context,
            "directory",
            "fileName"); //set destination
    //OR
    request.setDestinationInExternalFilesDir(context, "PATH");
    DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    final long downloadId = manager.enqueue(request); //start the download and return the id of the download. this id can be used to get info about the file (the size, the download progress ...) you can also stop the download by using this id     
}
Wajdi Chamakhi
  • 426
  • 5
  • 16
  • how can i get to know when the download has finished, 'cause i need to initiate some function on the downloaded file. – anant sophia May 08 '15 at 04:14
  • 1
    `DownloadManager.Query q = new DownloadManager.Query(); q.setFilterById(mDownloadId); Cursor cursor = manager.query(q); cursor.moveToFirst();` this is going to init the cursor from the Query. `int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));` => this gets you the total size of the file `int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));` => this gets you how much you did download from this file – Wajdi Chamakhi May 08 '15 at 16:33
  • @WajdiChamakhi What if you need to download multiple files at once? – Steve C. Apr 06 '16 at 05:46
0

call

connection.setDoInput(true);
connection.connect();

before

InputStream inputStream = connection.getInputStream();
Leo Lin
  • 681
  • 5
  • 8