Skip to content

Instantly share code, notes, and snippets.

@mo7amd89
Last active March 29, 2022 10:29
Show Gist options
  • Save mo7amd89/d5434c9ac7a5f310a9d86757afa9c8ad to your computer and use it in GitHub Desktop.
Save mo7amd89/d5434c9ac7a5f310a9d86757afa9c8ad to your computer and use it in GitHub Desktop.
Android Download file with DownloadManager
@SuppressLint("Range")
private boolean downloadUpdate() {
boolean flag = false;
try {
final File apk_file_path = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
if (apk_file_path.exists()) apk_file_path.delete();
Log.v(TAG, "Downloading request on url :" + BaseUrl);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(BaseUrl));
request.setDescription("Update the App تحديث التطبيق");
request.setTitle("Update ");
//set destination
final Uri uri = Uri.parse("file://" + apk_file_path);
request.setDestinationUri(uri);
// get download service and enqueue file
final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request);
//binding.progressBar.setVisibility(View.VISIBLE);
// new Thread(() -> {
boolean downloading = true;
while (downloading) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
Cursor cursor = manager.query(q);
if (cursor != null && cursor.moveToFirst()) {
cursor.moveToFirst();
@SuppressLint("Range") final int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
downloading = false;
flag = true;
Log.v(TAG, "STATUS_SUCCESSFUL");
}
if (status == DownloadManager.STATUS_FAILED) {
Log.i("FLAG", "Fail");
downloading = false;
flag = false;
break;
}
@SuppressLint("Range") int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
Log.v(TAG, "COLUMN_TOTAL_SIZE_BYTES " + bytes_total);
if (bytes_total != 0) {
final int dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);
runOnUiThread(new Runnable() {
@Override
public void run() {
binding.textView.setText((int) dl_progress + "/" + "100");
}
});
}
cursor.close();
} else {
cursor.close();
Log.v(TAG, "Downloading Failled");
downloading = false;
flag = false;
}
} // end of while llop
// }).start();
return flag;
} catch (Exception e) {
e.printStackTrace();
flag = false;
return flag;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment