>我正在开发一个Android应用程序,当用户播放时,我需要从我的网站获取指定的音频文件,但我不想每次都流式传输或下载它,只是第一次。所以我正在考虑缓存它并在用户需要时离线播放。因此,请建议任何方法。或者如果存在任何其他方法而不是缓存like downloading the actual file to file storage and play whenever needed
.
如果需要缓存文件,则应使用 createTempFile((。例如,以下方法从 URL 中提取文件名,并在应用的内部缓存目录中创建具有该名称的文件:
private File getTempFile(Context context, String url) {
File file;
try {
String fileName = Uri.parse(url).getLastPathSegment();
file = File.createTempFile(fileName, null,
context.getCacheDir());
} catch (IOException e) {
// Error while creating file
}
return file;
}
您还可以在此处查看有关缓存文件的更多信息。
https://developer.android.com/training/data-storage/files.html#WriteCacheFileInternal
希望这会有所帮助。