我正在制作一个可以下载并显示特殊文件的android库应用。现在,我需要编写一个可以在后台下载文件的服务!有服务样本吗?

我想将文件保存在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卡中。您可以使用AsysnTaskthread在后台运行此代码。

10-08 13:45