我正在制作一个可以下载和显示特殊文件的 android 图书馆应用程序。现在我需要写一个在后台下载文件的服务!有服务 sample 吗?
我想将文件保存在 SD 中,因为用户可以更新应用程序并且不应该错过下载的文件。
如果您对此有任何建议或意见,请写信给我。
最佳答案
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();
}
}
权限:要写入外部存储,您需要添加此权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
注意:您可以使用上面的代码将文件下载并保存在 SD 卡中。您可以使用 AsysnTask 在后台运行此代码或线程
。
关于android - 如何在后台使用服务下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8276913/