[英]How should I manage temporary downloads in Android app?
I have an async task which in doInBackgrund
is setting up a connection to perform a GET, takes the response to an OutputStream
and it ends up writing a file to sd. 我有一个异步任务,该任务在
doInBackgrund
正在建立连接以执行GET,将响应发送到OutputStream
,最终将文件写入sd。
Such file is actually an mp3 which will be reproduced once using a MediaPlayer
and forgotten, not ever used again. 这样的文件实际上是一个mp3文件,它将使用
MediaPlayer
进行一次复制并被遗忘,不再使用。
This is how I'm doing it all ... 这就是我所做的一切...
@Override
protected File doInBackground(String... params) {
try {
String urlString = ttsURL + URLEncoder.encode(params[0], "UTF-8");
URL url = new URL(urlString);
System.out.println(url.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36");
Log.d("QUERY PROPERTIES",urlConnection.getRequestProperties().toString());
urlConnection.connect();
if (urlConnection.getResponseCode() != 200) {
}
System.out.println(urlConnection.getContentEncoding() == null);
System.out.printf(urlConnection.getResponseMessage());
System.out.println(urlConnection.getHeaderFields().toString());
input = urlConnection.getInputStream();
File sdDir = getExternalStorageDirectory();
file = sdDir + "/" + params[0] + ".mp3";
output = new FileOutputStream(file);
int fileLength = urlConnection.getContentLength();
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
} catch (ProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
}
Log.i("Response", "Done");
return new File(file);
}
@Override
protected void onPostExecute(File f) {
MediaPlayer player = new MediaPlayer();
try {
player.setDataSource(f.toString());
} catch (IOException e) {
e.printStackTrace();
}
try {
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
player.start();
}
So, as it can be seen at onPostExecute
, that file is being used to play the audio. 因此,正如在
onPostExecute
可以看到的onPostExecute
,该文件正在用于播放音频。 Although I'm not deleting the file in the code I providing, I wonder what's best alternative for this case ... I know I could attempt to delete the file when the player it's at onPlaybackCompleted
state, but I'd like a way much simple and convenient approch for temporal files. 尽管我没有在提供的代码中删除文件,但我想知道这种情况下最好的替代方法是什么……我知道我可以在播放器处于
onPlaybackCompleted
状态时尝试删除该文件,但是我想做很多事情简单方便的临时文件处理方法。
使用单独的文件夹,并在确定用户离开您的应用程序后,清除该目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.