Skip to content

Instantly share code, notes, and snippets.

@sinadalvand
Last active July 26, 2021 17:37
Show Gist options
  • Save sinadalvand/1dd9cbb831ed73522c87f099dd2bcbc8 to your computer and use it in GitHub Desktop.
Save sinadalvand/1dd9cbb831ed73522c87f099dd2bcbc8 to your computer and use it in GitHub Desktop.
Download Code
public void download(String url,String path){
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
String filePath = Environment.getExternalStorageDirectory().getPath().toString() + "/app.apk";
File f = new File(filePath);
DataOutputStream fos = new DataOutputStream(new FileOutputStream(f, false));
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = stream.read(data)) != -1) {
total += count;
if (contentLength > 0) {
Log.e("Downloader","Percent: "+((int) (total * 100 / contentLength)));
}
fos.write(data, 0, count);
}
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment