【发布时间】:2013-03-14 11:25:47
【问题描述】:
我希望我的应用从 url 下载视频。 现在我想将下载文件写入我的 SD 卡。
我尝试了一些不同的脚本,但没有收到android.os.NetworkOnMainThreadException 异常。但是我的应用程序崩溃了。
Download a file programatically on Android
What is best way to download files from net programatically in android?
有人知道如何创建工作方法吗? 要解决这个异常,它必须是一个异步任务。
public static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(Exception e) {
Log.e("theple", "" + e);
}
}
日志:
03-14 12:09:46.535: E/theple(6987): android.os.NetworkOnMainThreadException
【问题讨论】:
-
在此处粘贴您的日志。
-
它必须是异步任务。您只需要在后台线程中运行它。 AsyncTask 只是实现这一目标的一种方式。
-
@AleksG 你有一个例子让我让它工作吗?
标签: android asynchronous download task mp4