I am trying to cancel downloading task with id.
I get id from
DownloadManager manager = (DownloadManager) getApplicationContext().getSystemService(Context.DOWNLOAD_SERVICE);
downloadId = manager.enqueue(req);
I want to stop download when on user button click, but I tested to stop download after 10% of being downloaded in this test code.
the code "manager.remove(downloadId);" is working perfect to clear downloading noti and stopping the task with requested ID. But it also stop the app too, app error also occur after that code. please how can I solve the problem.
new Thread(new Runnable() {
#Override
public void run() {
boolean downloading = true;
while (downloading) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
cursor = manager.query(q);
cursor.moveToFirst();
int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
final int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
downloading = false;
}
final int dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);
String finalDl_size;
int dl_size = (int) (bytes_total/(1024*1024));
finalDl_size = Integer.toString(dl_size)+" MB";
if(dl_size>1000){dl_size=(int) (bytes_total/(1024*1024*1024));
finalDl_size = Integer.toString(dl_size)+" GB";}
final String finalDl_size1 = finalDl_size;
runOnUiThread(new Runnable() {
#Override
public void run() {
btndownload.setText("Downloading "+Integer.toString(dl_progress)+"% , "+ finalDl_size1);
if(dl_progress==100){
btndownload.setBackgroundColor(Color.GREEN);
btndownload.setText("Download Completed");
}
else if(dl_progress>10){
try{
manager.remove(downloadId); ///// Stop after 10%
}
catch (Exception e){}
}
}
});
cursor.close();
}
}
}).start();
Logcat Output
Please Kindly help me. Thank you in advance.
Try this
if (cursor.getCount() > 0)
manager.remove(downloadId); ///// Stop after 10%
Related
When I use Environment.getExternalStorageDirectory()+File.separator+"applicationAsbid"; I expect to create a directory in device's external storage but it is created in Cache folder.
Why?
What happened and what should I do?
UPDATE:
This is my method:
root = Environment.getExternalStorageDirectory().getPath();
myDir = new File(root);
myDir.mkdir();
private void downloadDoc(ProgressBar progressBar, CircularImageView imageView, String name, String link, SendMessageViewModel messageData) {
progressBar.setVisibility(View.VISIBLE);
Uri uri = Uri.parse(link);
DownloadManager downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle("در حال دانلود");
request.setDescription("لطفا منتظر بمانید...");
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
request.setDestinationInExternalFilesDir(mContext, root, name);
final long id = downloadManager.enqueue(request);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(id);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
long downloadedBytes = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
long totalBytes = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
final int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
final int percent = (int) ((downloadedBytes * 100) / totalBytes);
((Activity) mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
progressBar.setProgress(percent);
if (percent == 100) {
Toast.makeText(mContext, "دانلود با موفقیت انجام شد", Toast.LENGTH_SHORT).show();
timer.purge();
timer.cancel();
for (int item : downloadList) {
if (Integer.parseInt(messageData.getId()) == item) {
imageView.setImageResource(R.drawable.ic_doc3);
imageView.setContentDescription("after");
progressBar.setVisibility(View.GONE);
}
}
}
}
});
}
}
}, 0, 100);
}
At the end I should say this is not my own code and my colleague has written that. We check that and found nothing so I aske here.
We use Downloadmanager in another class and for download something else. That works fine but here it does not work.
Second Update:
I changed my code to this:
root = Environment.getExternalStorageDirectory().getPath() + "/Dehkade/Chat1";
myDir = new File(root);
if (!myDir.exists()) {
if (!myDir.mkdir()) {
Toast.makeText(mContext," ...sorry could not create directory...",Toast.LENGTH_SHORT).show();
return;
}
}
But it does not work too, in fact the Toast is executed. Also I use this code:
request.setDestinationInExternalFilesDir(mContext, null, name);
Instead of this code:
request.setDestinationInExternalFilesDir(mContext, root, name);
But nothing changes.
I am working on an android app in which i am using DownloadManager to download a file from a server.
Problem
While the file download is in progress, I want to show the download progress via progress bar. File is downloaded successfully but I am not able to show the download progress.
Code I use to show progress
private void startAppDownload() {
...
// code to show download progress
new Thread(new Runnable() {
#Override
public void run() {
boolean isDownloading = true;
int downloadStatus, totalBytesDownloaded, totalBytes;
DownloadManager.Query downloadQuery = new DownloadManager.Query();
downloadQuery.setFilterById(downloadID);
Cursor cursor = downloadManager.query(downloadQuery);
cursor.moveToFirst();
while (isDownloading) {
totalBytesDownloaded = cursor.getInt(
cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
);
totalBytes = cursor.getInt(
cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
);
downloadStatus = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if(downloadStatus == DownloadManager.STATUS_SUCCESSFUL) {
isDownloading = false;
}
final int downloadProgress = (int) ((double)totalBytesDownloaded / (double)totalBytes * 100f);
runOnUiThread(new Runnable() {
#Override
public void run() {
downloadProgressBar.setProgress(downloadProgress);
}
});
}
cursor.close();
}
}).start();
}
I logged the totalBytesDownloaded variable but it is always zero and the totalBytes variable is always -1.
This causes downloadProgress variable to always be zero, hence progress bar shows no progress.
Question
What am I doing wrong here? Why is totalBytesDownloaded variable always equal to zero and totalBytes variable always -1?
You have a Logic error, Your Query is out of the while loop where the UI is updated
private void startAppDownload() {
new Thread(new Runnable() {
#Override
public void run() {
boolean isDownloading = true;
int downloadStatus, totalBytesDownloaded, totalBytes;
while (isDownloading) {
DownloadManager.Query downloadQuery = new DownloadManager.Query();
downloadQuery.setFilterById(downloadID);
Cursor cursor = downloadManager.query(downloadQuery);
cursor.moveToFirst();
totalBytesDownloaded = cursor.getInt(
cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
);
totalBytes = cursor.getInt(
cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
);
downloadStatus = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if(downloadStatus == DownloadManager.STATUS_SUCCESSFUL) {
isDownloading = false;
break;;
}
final int downloadProgress = (int) ((double)totalBytesDownloaded / (double)totalBytes * 100f);
runOnUiThread(new Runnable() {
#Override
public void run() {
downloadProgressBar.setProgress(downloadProgress);
}
});
}
cursor.close();
}
}).start();
}
I try to perform downloading the file using DownloadManager. Everything works fine except LG devices. Here is my code:
private void downloadFile(FileInfo fileInfo) {
private DownloadManager manager = (DownloadManager) MyApp.getSingleton().
getApplicationContext().getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("https://"
+ MyPreference.getInstance().getBaseUrl()
+ "/api/v3/files/"
+ fileId
+ "/get"));
request.setDescription(MyApp.getSingleton().getApplicationContext().getString(R.string.downloading));
request.setTitle(fileInfo.getmName());
request.addRequestHeader("Authorization", "Bearer " + MyPreference.getInstance().getAuthToken());
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
File dir = new File(FileUtil.getInstance().getDownloadedFilesDir());
if(!dir.exists()){
dir.mkdirs();
}
request.setDestinationUri(Uri.fromFile(new File(FileUtil.getInstance().getDownloadedFilesDir() + File.separator + fileInfo.getmName())));
downloadId = manager.enqueue(request);
new Thread(() -> {
boolean downloading = true;
while (downloading) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
Cursor cursor = manager.query(q);
cursor.moveToFirst();
int bytes_downloaded = 0;
long bytes_total = 0;
try {
bytes_downloaded = cursor.getInt(cursor
.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
bytes_total = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
} catch (CursorIndexOutOfBoundsException e) {
e.printStackTrace();
cursor.close();
break;
} catch (IllegalArgumentException e){
e.printStackTrace();
cursor.close();
break;
}
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_FAILED) {
downloading = false;
cursor.close();
onDownloadFail();
break;
} else if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
downloading = false;
cursor.close();
break;
}
if (bytes_total > 0) {
final int dl_progress = (int) ((bytes_downloaded * 100L) / bytes_total);
onProgress(dl_progress);
}
cursor.close();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
On LG devices line
bytes_total = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
returns -1.
Download notification appears in notification bar and disappears immediately after few milliseconds. No one exception, no one enter this code section
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_FAILED) {
downloading = false;
cursor.close();
onDownloadFail();
break;
}
else if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
downloading = false;
cursor.close();
break;
}
Just nothing. So internal while() cycle work forever.
Tested on devices LG D802 and LG G3 S. Both devices show the same behavior.
I faced the same issue and found the solution for this. You need to make sure all the directories exists before init Download Manager.
Example: in my case the path to my File is
/storage/emulated/0/MyFolder/n.jpeg
so I have to make sure MyFolder directory exists before init Download Manager.
I'm trying to show the download progress of DownloadManager in percentage as shown in the notification bar.
I've read up some answer here.
However, the method provided is using the Thread.
As my understanding,Thread is not a good way.
Is there any alternative way to do the same thing?
Or using Thread is just fine in this case?
Edit 1:
Added in the code in my project.
new Thread(new Runnable() {
#Override
public void run() {
boolean downloading = true;
while (downloading) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
Cursor cursor = downloadManager.query(q);
cursor.moveToFirst();
int bytes_downloaded = cursor.getInt(cursor
.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
downloading = false;
}
final int dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);
((Activity) mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
holder.mTextView.setText(String.valueOf(dl_progress) + "%");
}
});
cursor.close();
}
}
}).start();
The question is I have implemented android downloadmanager to download files from internet. how can i pause and resume the download? i have read lots of posts and searched google but could not find a working answer. Thanks
DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(url + fileName));
downloadRequest.setTitle("Downloading: ");
downloadRequest.setDescription("Description");
downloadRequest.allowScanningByMediaScanner();
downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,applicationApk);
manager = (DownloadManager) downloadActivity.getSystemService(Context.DOWNLOAD_SERVICE);
downloadId = manager.enqueue(downloadRequest);
new Thread(new Runnable()
{
#Override
public void run()
{
int fileSize = size;
downloadProgress.setProgress(0);
downloadProgress.setMax(fileSize);
sizeInBytes = fileSize * 1024 * 1024;
DownloadManager.Query q = new DownloadManager.Query();
//q.setFilterById(downloadId);
downloading = true;
while (downloading)
{
Cursor cursor = manager.query(q);
if (cursor.moveToFirst())
{
int sizeIndex = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
int downloadedIndex = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
long size = cursor.getInt(sizeIndex);
long downloaded = cursor.getInt(downloadedIndex);
if (size != -1) dl_progress = downloaded * fileSize / size;
}
downloadProgress.setProgress((int) dl_progress);
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL)
{
downloading = false;
}
cursor.close();
}
}
}).start();