在我的Android应用程序中,我必须从网址下载一些视频。为此,我使用此功能:
private void saveVideoToSDcard(String video) throws IOException {
URL url = new URL(video);
long startTime = System.currentTimeMillis();
String name = video.substring(video.lastIndexOf("/") + 1);
System.out.println("image download beginning: " + name);
// Open a connection to that URL
ucon = url.openConnection();
// this timeout affects how long it takes for the app to realize there's
// a connection problem
ucon.setReadTimeout(TIMEOUT_CONNECTION);
ucon.setConnectTimeout(TIMEOUT_SOCKET);
// Define InputStreams to read from the URLConnection.
// uses 3KB download buffer
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
FileOutputStream outStream = new FileOutputStream(
Environment.getExternalStorageDirectory() + "/Downloads/"
+ name);
byte[] buff = new byte[5 * 1024];
// Read bytes (and store them) until there is nothing more to read(-1)
int len;
while ((len = inStream.read(buff)) != -1) {
outStream.write(buff, 0, len);
}
// clean up
outStream.flush();
outStream.close();
inStream.close();
System.out.println("download completed in "
+ ((System.currentTimeMillis() - startTime) / 1000) + " sec");
}
我在onCreate()方法上调用了这个函数:
for (int j = 0; j < jArray.length(); j++) {
if (target[j].endsWith(".mp4")) {
System.out.println("video de downloadat");
String name = target[j]
.substring(target[j].lastIndexOf("/") + 1);
try {
saveVideoToSDcard(target[j]);
target[j] = Environment.getExternalStorageDirectory()
+ "/Downloads/" + name;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
其中target[]
是包含视频网址的数组。
视频已下载到Downloads
文件夹,但我遇到此问题:我暂时下载了2个视频:第一个视频的持续时间为1:17,第二个视频的持续时间为2:38。如果我打开第一个视频,它会播放10秒钟,之后会意外关闭。第二个视频没有这个问题,它工作正常。你知道为什么我有这个问题吗?
欢迎任何想法。提前谢谢。