我希望我的應用從網址下載視頻。 現在我想寫下載文件到我的SD卡。Android手機在下載視頻(mp4)文件時崩潰
我嘗試了一些不同的腳本,我沒有收到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
在這裏粘貼你的日誌。 – 2013-03-14 11:30:50
它並不是一個異步任務。所有你需要的是在後臺線程中運行它。 AsyncTask只是實現這一點的一種方式。 – 2013-03-14 11:35:36
@AleksG你有一個例子讓我得到這個工作? – 2013-03-14 11:51:49