anant sophia
anant sophia

Reputation: 55

Download file from a webserver into android external storage

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.

Upvotes: 1

Views: 2927

Answers (2)

Wajdi Chamakhi
Wajdi Chamakhi

Reputation: 426

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     
}

Upvotes: 4

Leo Lin
Leo Lin

Reputation: 711

call

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

before

InputStream inputStream = connection.getInputStream();

Upvotes: 0

Related Questions