我有一个异步任务,在doInBackgrund
中设置连接以执行GET,将响应发送到OutputStream
并最终将文件写入sd。
这样的文件实际上是一个mp3,它将使用MediaPlayer
再现一次并被遗忘,而不是再次使用过。
这就是我所做的一切......
@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();
}
因此,正如onPostExecute
所见,该文件正用于播放音频。虽然我没有删除我提供的代码中的文件,但我想知道这个案例的最佳替代方案...我知道我可以尝试在播放器处于onPlaybackCompleted
状态时删除该文件,但我会就像一个简单方便的临时文件approch。
答案 0 :(得分:1)
使用单独的文件夹,当您确定用户离开您的应用时,请清除该目录。