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.

4

2 回答 2

4

您可以使用AndroidDownloadManager

该类处理文件下载的所有步骤,并为您提供有关进度的信息...

您应该避免使用线程。

这是你如何使用它:

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     
}
于 2015-05-07T16:37:02.733 回答
0

称呼

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

InputStream inputStream = connection.getInputStream();
于 2015-05-07T16:29:30.933 回答