protected Long doInBackground(Object... params) {
Context context = (Context) params[0];
String name = (String) params[1];
String urlString = (String) params[2];
File mediadir = context.getDir("tvr", Context.MODE_PRIVATE);
try {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
connection.connect();
int lenghtOfFile = connection.getContentLength();
InputStream is = url.openStream();
Log.d("DOWNLOAD NAME",name);
File new_file = new File(mediadir, name);
FileOutputStream fos = new FileOutputStream(new_file.getPath());
byte data[] = new byte[1024];
int count = 0;
long total = 0;
int progress = 0;
while ((count=is.read(data)) != -1){
total += count;
int progress_temp = (int)total*100/lenghtOfFile;
if(progress_temp%10 == 0 && progress != progress_temp){
progress = progress_temp;
}
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("DOWNLOAD ERROR", e.toString());
}
return null;
}
正如我现在所理解的那样,我通过流下载文件并将数据流式传输到文件中。所以实际上文件是从数据的第一个字节开始创建的。
现在,另一方面我通过在目录中查找文件然后播放文件来播放内部目录中的文件:
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setDisplay(holder);
FileInputStream fileInputStream = new FileInputStream(path);
mediaPlayer.setDataSource(fileInputStream.getFD());
fileInputStream.close();
mediaPlayer.prepare();
mediaPlayer.start();
现在这个问题是文件即使没有完全下载也会播放!
这是真的吗?如果是这样,在尝试播放文件之前,我该如何检查文件是否完整?
答案 0 :(得分:3)
是的,这是一个有效的方案,因为在许多情况下,您的下载速度将慢于MediaPlayer
的阅读和播放速度。
当您使用AsyncTask时,可以通过调用onPostExecute()
方法中的播放代码来解决此问题,因为只有在doInBackground()
方法中的所有工作完成后才会运行。 / p>