如何下载文件,在后台服务? [英] how to download file with service in the background?
问题描述
我在做一个机器人库的应用程序,可以下载并显示特殊文件。现在我需要编写下载文件在后台的服务!是否有样品服务?
和我要保存在SD文件,因为用户可以更新应用程序,不应该错过下载的文件。
如果您有建议或意见对于这一点,写信给我,请。
尝试{
网址URL =新的URL(URL从apk文件被下载);
HttpURLConnection的的URLConnection =(HttpURLConnection类)url.openConnection();
urlConnection.setRequestMethod(GET);
urlConnection.setDoOutput(真正的);
urlConnection.connect();
文件SD卡= Environment.getExternalStorageDirectory();
档案文件=新的文件(SD卡,FILENAME.EXT);
FileOutputStream中fileOutput =新的FileOutputStream(文件);
InputStream中的InputStream = urlConnection.getInputStream();
byte []的缓冲区=新的字节[1024];
INT BufferLength中= 0;
而(量(bufferLength = inputStream.read(缓冲液))大于0){
fileOutput.write(缓冲液,0,BufferLength中);
}
fileOutput.close();
}赶上(MalformedURLException异常E){
e.printStackTrace();
}赶上(IOException异常E){
e.printStackTrace();
}
}
权限::要写入外部存储,则需要添加该权限:
<使用-权限的Android:名称=android.permission.WRITE_EXTERNAL_STORAGE/>
注意::您可以使用上面code获得下载并保存在SD卡上的文件。您可以使用 AsysnTask 或线程运行此code在后台
。
I'm making a android library app that can download and show special files. now I need to write a service that download file in background! are there samples for services?
and I want to save files in SD, because users can update app and don't should miss downloaded files.
If you have a suggest or opinion for this, write me, please.
try {
URL url = new URL("url from apk file is to be downloaded");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "filename.ext");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Permission: To write to external storage, you need to add this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Note: you can use above code to get the file downloaded and saved in the SD card. You can run this code in background using AsysnTask or thread
.
这篇关于如何下载文件,在后台服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!