在一个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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句