几个要点:
1.读取url地址的视频文件内容
2.访问存储空间并保存
3.用videoView播放
4.退出时清空文件
与上一篇文章中的下载图片类似,在asyncTask中打开url地址的内容
在这里,我们虽然可以用
for (int i = 0; i < params.length; i++)
读取(只要改一下存储文件的名字,加上 i 做标识就可以了),不过我们暂时只下载一个视频文件
先确定一个存储路径
File f = new File(Environment.getExternalStorageDirectory()
+ "/test");
然后检查这个路径是否存在,不存在就新建一个,在app运行的时候我们可以跳出到管理器查看是不是有一个test文件夹创建了
创建路径后,我们就可以将url的内容放进demo.mp4中了
未免用户以为app停掉了或者乱按其他按钮(这里没别的按钮了。。。)
我们在asyncTask中加入progressDialog,并在任务完成后自动取消掉dialog
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progress.show();
}
并且,我们这里约定下载完成后dialog消失,videoView自动播放视频
VideoView用法很简单,只要findViewById然后确定路径即可(最简单的用法,还有复杂的大家可以看别的资料)
class load_video extends AsyncTask<String, Integer, Void> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progress.show();
}
@Override
protected Void doInBackground(String... params) {
int count;
for (int i = 0; i < params.length; i++) {
try {
URL url = new URL(params[i]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(
url.openStream(), 8192);// 1024*8
File f = new File(Environment.getExternalStorageDirectory()
+ "/test");
if (f.isDirectory()) {
System.out.println("exist!");
} else {
System.out.println("not exist!");
f.mkdirs();
}
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/test/demo.mp4");
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progress.dismiss();
VideoView videoView = (VideoView) findViewById(R.id.videoview);
File videoFile = new File(Environment.getExternalStorageDirectory()
.toString() + "/test/demo.mp4");
videoView.setVideoPath(videoFile.getPath());
videoView.start();
}
}
补上在onCreate中progressDialog的新建和AsyncTask的启动
progress = new ProgressDialog(this);
progress.setMessage("Loading...");
progress.setCancelable(false);
new load_video()
.execute("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");