I want my app to download a video from an url. For now I want to write download the file to my sd card.
I tried some different scripts, I don't receive an android.os.NetworkOnMainThreadException
exception. But my application crashes.
Download a file programatically on Android
What is best way to download files from net programatically in android?
Does anyone know how to create a working method? To solve this exception it has to be an async task.
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);
}
}
Logs:
03-14 12:09:46.535: E/theple(6987): android.os.NetworkOnMainThreadException