从网络服务器下载文件到 android 外部存储

Download file from a webserver into android external storage

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

执行没有错误,但是没有下载文件。请提出建议。

致电

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

之前

InputStream inputStream = connection.getInputStream();

您可以使用 AndroidDownloadManager.

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

你应该避免使用线程。

这是您的使用方式:

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     
}