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

标签 android downloading-website-files

在 Android 应用程序中,我试图将文件从 Web 服务器下载到外部存储上的/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();
    }

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

最佳答案

您可以使用 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     
}

关于android - 从网络服务器下载文件到安卓外部存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30106405/

相关文章:

android - 从位图分配 Renderscript

C# 下载文件不起作用

android - 使用多个 fragment 设置 RadioButton.setChecked

java - 为什么我无法导入 GoogleSignInClient 类?

java - 用java获取网站的资源文件夹

batch-file - wget 未被识别为内部或外部命令

java - 使用 HTTP 请求下载文件的一部分

javascript - 如何从自定义 Android 应用程序启动 uber eats 应用程序

java - 如何在android中读取USSD消息响应