Скачать файл с веб-сервера во внешнее хранилище Android

В приложении для Android я пытаюсь загрузить файл с веб-сервера в папку /Download на внешнем хранилище. код загрузки выполняется в HandlerThread в сервисе.

Сервис выполняет другие функции помимо загрузки файла. код для скачивания выглядит так:

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();
    }

В выполнении нет ошибки, но файл не загружен. Пожалуйста, предложите.

2 ответа

Решение

Вы можете использовать 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     
}

Вызов

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

до

InputStream inputStream = connection.getInputStream();
Другие вопросы по тегам