![](/img/trans.png)
[英]How to download a file from Firebase Storage to the External_Storage of Android
[英]Download file from a webserver into android external storage
在一个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
}
呼叫
connection.setDoInput(true);
connection.connect();
之前
InputStream inputStream = connection.getInputStream();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.