DownloadManager double download - android

I have the following problem: Whenever I download a file with the DownloadManager it is downloaded twice (saved in the fashion "filename.extension" and "filename-1.extension"). Here is my code:
public void download() {
Request request = new Request(Uri.parse(_wrapper.getURL()));
request.setTitle(getFileName(_wrapper.getURL()));
request.setVisibleInDownloadsUi(false);
request.setDestinationInExternalFilesDir(_context, null, "/" + getFileName(_wrapper.getURL()));
_downloadID = _downloadManager.enqueue(request);
}
public BroadcastReceiver getDownloadFinishedBroadcastReceiver() {
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context pContext, Intent pIntent) {
String action = pIntent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
Query query = new Query();
query.setFilterById(_downloadID);
Cursor cursor = _downloadManager.query(query);
if (cursor.moveToFirst()) {
File file = new File(ScruloidConstants.APPLICATION_DIRECTORY);
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
String path = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
_wrapper.setFilePath(path);
_wrapper.setLastDownloaded(new Date());
if (_listener != null) {
_listener.onDownloadProjectTaskFinished(new TaskResult<ProjectWrapper>(_wrapper));
}
}
else if (status == DownloadManager.STATUS_FAILED) {
int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
DownloadFailedException ex = new DownloadFailedException(reason);
if (_listener != null) {
_listener.onDownloadProjectTaskFinished(new TaskResult<ProjectWrapper>(ex));
}
}
}
}
}
};
return receiver;
}
The ProjectWrapper _wrapper is just a simple Class that holds data, no logic is done there. The _listener just displays on the callback method a little Toast message. I debugged my app to make shure the download() Method is invoked only once. I hope you can help me find the error.

Unfortunately, DownloadManager is buggy and doesn't work correctly on all devices. Your problem is reported here: https://code.google.com/p/android/issues/detail?id=18462

I've got the same error on mobile devices with API 21, I've made a workaround to verify before creating a request, if the file name used to set de request destination was equal one of the last files already downloaded, or if its a substring of any previews downloaded
if (!mLastMediaDownloadedId.any { it.contains(outputFile.name) }) {
mLastMediaDownloadedId.add(outputFile.name)
val url =
AppConstants.AWS_MEDIA_BUCKET_PATH + scoutObjectType.endPoint() + "$scoutObjectId.png"
val request = DownloadManager.Request(Uri.parse(url))
.setDestinationUri(Uri.fromFile(outputFile))
.setTitle("Downlading media")
.setDescription("Downloading image medias")
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
.setAllowedOverRoaming(true)
.setAllowedOverMetered(true)
val downloadId = it.enqueue(request)
downloadIds.add(downloadId)
downloadId
}
and where "outputFile" is the file name itself to be downloaded, in your case this should be "filename.extension"
PS: Sorry for the Kotlin code, but it should be a good representation for the workaround itself

Related

Download Manager with Google Drive URL

I'm trying to download a file stored in Google Drive using android DownloadManager.
I get the sign in token from Google like following:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(AppConfig.getInstance().get("google_client_id"))
.requestProfile()
.requestEmail()
.build();
I receive a notification with google drive file url and i pass it to the DownloadManager, passing to it the token:
String cookie = CookieManager.getInstance().getCookie(d.getURL());
request.addRequestHeader("Cookie",cookie);
request.addRequestHeader("Authorization", "OAuth " + profile.getToken());
//d is the document object, that contains url, file name, etcc
//Profile is a simple object class that hold the user data taken from sign Google, like token, name, email, etcc
Using a simple Broadcast Receiver to manage the download result (ACTION_DOWNLOAD_COMPLETE).
The download is done successfully, but the file is corrupted.
If i try to open it, the device (and pc) gives me a format error.
The file contains a HTML code of a Google page that says that there war an error, no more.
(The account that i'm using is enabled to read and dwonload the document form this specific drive storage)
Is this the correct way to download a Google Drive file using DownloadManager? Is it possible to do that?
Try whether this helps...
As in #saddamkamal 's answer, use the Google Drive download URL.
AsyncTask.execute(new Runnable() {
#Override
public void run() {
DownloadManager downloadmanager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("https://drive.google.com/uc?id=<FILE_ID>&export=download");
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle("My File");
request.setDescription("Downloading");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "file.extension");
downloadmanager.enqueue(request);
}
});
You can also downlaod file form google via this method
Refer to this Url
https://drive.google.com/uc?id=<FILE_ID>&export=download
Replace <FILE_ID> with your shareable file ID.
Further you can take help from this solution Download a file with Android, and showing the progress in a ProgressDialog
You can use the doInBackground function in it to solve your query.
Since file is downloaded.
Check the size of file in Google drive and your android.
Then make sure your file extension is correct.
Because file extension may not be present and android will treat it as binary file.
Now you have file extension in android. Install proper application to open it.
This is updated code
public class MainActivity extends AppCompatActivity {
private Button btn_download;
private long downloadID;
// using broadcast method
private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Fetching the download id received with the broadcast
long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
//Checking if the received broadcast is for our enqueued download by matching download id
if (downloadID == id) {
Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_download = findViewById(R.id.download_btn);
// using broadcast method
registerReceiver(onDownloadComplete,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
beginDownload();
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
// using broadcast method
unregisterReceiver(onDownloadComplete);
}
private void beginDownload(){
String url = "http://speedtest.ftp.otenet.gr/files/test10Mb.db";
String fileName = url.substring(url.lastIndexOf('/') + 1);
fileName = fileName.substring(0,1).toUpperCase() + fileName.substring(1);
File file = Util.createDocumentFile(fileName, context);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url))
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN)// Visibility of the download Notification
.setDestinationUri(Uri.fromFile(file))// Uri of the destination file
.setTitle(fileName)// Title of the Download Notification
.setDescription("Downloading")// Description of the Download Notification
.setRequiresCharging(false)// Set if charging is required to begin the download
.setAllowedOverMetered(true)// Set if download is allowed on Mobile network
.setAllowedOverRoaming(true);// Set if download is allowed on roaming network
DownloadManager downloadManager= (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadID = downloadManager.enqueue(request);// enqueue puts the download request in the queue.
// using query method
boolean finishDownload = false;
int progress;
while (!finishDownload) {
Cursor cursor = downloadManager.query(new DownloadManager.Query().setFilterById(downloadID));
if (cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch (status) {
case DownloadManager.STATUS_FAILED: {
finishDownload = true;
break;
}
case DownloadManager.STATUS_PAUSED:
break;
case DownloadManager.STATUS_PENDING:
break;
case DownloadManager.STATUS_RUNNING: {
final long total = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
if (total >= 0) {
final long downloaded = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
progress = (int) ((downloaded * 100L) / total);
// if you use downloadmanger in async task, here you can use like this to display progress.
// Don't forget to do the division in long to get more digits rather than double.
// publishProgress((int) ((downloaded * 100L) / total));
}
break;
}
case DownloadManager.STATUS_SUCCESSFUL: {
progress = 100;
// if you use aysnc task
// publishProgress(100);
finishDownload = true;
Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();
break;
}
}
}
}
}
}

Is there a simpler way to check which download has been completed?

I'm currently creating an app that needs to download a couple of videos then save the local path of it on a SQLite database.
At first, I wanted to get the URL of the video I downloaded but I can't seem to find anything that discusses about it. I tried to get COLUMN_MEDIAPROVIDER_URI and COLUMN_URI from the intent passed on the BroadcastReceiver for DownloadManager.ACTION_DOWNLOAD_COMPLETE but they return null.
Then I found about EXTRA_DOWNLOAD_ID. But if I use that, I still need to use something like a new HashMap that got the EXTRA_DOWNLOAD_ID of my download and the id of the video on my SQLite database for checking which is which.
I'm fine with that but I want to know if there's an easier way to do the thing I want.
I did this using OkHttp, as follows:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(YOUR_URL)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// ERROR MESSAGE
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
response.body().byteStream(); // byteStream with your result.
}
}
});
Another thing, maybe would be better if you store the videos on memory and just the address in your SQLite.
Using the code below from the SO question here
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
// get the DownloadManager instance
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Query q = new DownloadManager.Query();
Cursor c = manager.query(q);
if(c.moveToFirst()) {
do {
String name = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
Log.i("DOWNLOAD LISTENER", "file name: " + name);
} while (c.moveToNext());
} else {
Log.i("DOWNLOAD LISTENER", "empty cursor :(");
}
c.close();
}
}
and saving the download id on my ArrayList I was able to make a simpler way to check which download is finished.
I modified it to look like this for my use case.
Cursor c = dlMgr.query(new DownloadManager.Query());
boolean found = false;
if(c.moveToFirst()) {
do {
String dlFilePath = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
int dlId = Integer.parseInt( c.getString(c.getColumnIndex(DownloadManager.COLUMN_ID)) );
for(int x = 0; x < vidArrLst.size(); x++){
VideoAd va = vidArrLst.get(x);
if(va.getDownloadId() == dlId){
dbHelper.updateLocalPath(va.getVideoId(), dlFilePath);
va.setLocalPath(dlFilePath);
found = true;
break;
}
}
} while (c.moveToNext() && !found);
} else {
Log.d(TAG, "empty cursor :(");
}
UPDATE:
Sometimes this method will show that 2 downloads finished with the same file name which results to a video item to not have a local path. What I did is check if the local path is empty, download id is greater than 0, and if the download id is still downloading before playing a video so I can redownload a video and fix the gap and play the local file the next time the video needs to be played.

Android Download Manager. status is always pending

I try to use Download Manager to download some files form specific URL,
but the download request was never completed.
So I log some information to see what went wrong, it turns out the request is always in pending status, and the COLUMN_REASON is 0 which I couldn't find the corresponding description on the document.
COLUMN_STATUS: 1
COLUMN_REASON: 0
COLUMN_TOTAL_SIZE_BYTES: -1
COLUMN_BYTES_DOWNLOADED_SO_FAR: 0
Here is how to start a download.
val req = DownloadManager.Request(uri).apply {
addRequestHeader("Cookie", cookie)
allowScanningByMediaScanner()
setTitle(fullname)
setDescription(/* description text */)
setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, fullname)
}
val downloadId = downloadManager.enqueue(req)
And log information for debugging.
val filterQuery = DownloadManager.Query().setFilterById(downloadId)
val cursor = downloadManager.query(filterQuery)
if (cursor.moveToFirst()) {
val total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
val current = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
val status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
val reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON))
Log.d("App", "status: " + status.toString())
Log.d("App", "reason: " + reason.toString())
Log.d("App", "total: " + total.toString())
Log.d("App", "current: " + current.toString())
}
So what's a possible reason that status of request was always pending and how do I debug it?
Any help is going to be appreciated.
In my case, settings up a VPN seem to solve this problem. It looks like google services have been blocked in my network and after I set up a system global VPN the issue has gone.
DownloadManager outputs its logs to logcat but not under your application's id, so you'll need to show logs for all apps. There should clues to the failed download in there. For example, here are a couple of my failure cases.
D/DownloadManager: [1988] Starting
W/DownloadManager: [1988] Stop requested with status 500: Internal Server Error
D/DownloadManager: [1988] Finished with status WAITING_TO_RETRY
and
W/DownloadManager: [1988] Stop requested with status 403: Unhandled HTTP response: 403 Forbidden
You have to wait(delay) before checking the status or set the download ID every time in a timer.
enqueue seems to return the download ID too late.
My code works very well:
private void startDownload(View v)
{
Uri uri=Uri.parse("http://example.com/app/name.apk");
DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request req = new DownloadManager.Request(uri)
.setTitle(title)
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
|DownloadManager.Request.NETWORK_MOBILE)
.setDescription("downloading")
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"name.apk");
downloadId = mgr.enqueue(req);
getDownloadStatus();
}
check status method
private void getDownloadStatus()
{
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = ((DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE))
.query(query);
if (cursor.moveToFirst())
{
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
query.setFilterById(downloadId);
Cursor cursor = ((DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE))
.query(query);
cursor.moveToFirst();
int status=cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_RUNNING) {
Log.i("DM_STATUS","status is "+" running");
}else if (status == DownloadManager.STATUS_SUCCESSFUL) {
Log.i("DM_STATUS","status is "+" success");
timer.cancel();
}
}
}, 100,1);
}
}

Unable to send MMS using SmsManager

I am trying to make an app that would send a MMS without using the native Android messaging app. I followed the example here. My log statements seem to be correctly printing, but I can't figure out why the MMS is not being sent.
Also on a different note, I am a bit confused about where in the example the attachment (like an image) is being selected to send as MMS. I tried to import the demo into Android Studio but I ran into issues.
My function for sending MMS is below:
public void sendMMS() {
Log.d(TAG, "sendMMS()");
Random random = new Random();
final String fileName = "send." + String.valueOf(Math.abs(random.nextLong())) + ".dat";
final File mSendFile = new File(mContext.getCacheDir(), fileName);
// Making RPC call in non-UI thread
AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
#Override
public void run() {
final byte[] pdu = buildPdu();
Uri writerUri = (new Uri.Builder())
.authority("com.example.appname")
.path(fileName)
.scheme(ContentResolver.SCHEME_CONTENT)
.build();
Log.d(TAG, "sendMMS(): Uri: " + writerUri.toString());
FileOutputStream writer = null;
Uri contentUri = null;
try {
writer = new FileOutputStream(mSendFile);
writer.write(pdu);
contentUri = writerUri;
Log.d(TAG, "sendMMS(): just wrote file");
} catch (final IOException e) {
Log.d(TAG, "sendMMS(): FAILED: couldn't write file");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
}
}
}
if (contentUri != null) {
SmsManager.getDefault().sendMultimediaMessage(mContext, contentUri, null, null, null);
Log.d(TAG, "sendMMS(): just sent");
} else {
Log.d(TAG, "sendMMS(): FAILED: couldn't write file so didn't send");
}
}
});
}
Helper functions
private byte[] buildPdu() {
final SendReq req = new SendReq();
// from
final String lineNumber = getSimNumber();
if (!TextUtils.isEmpty(lineNumber)) {
req.setFrom(new EncodedStringValue(lineNumber));
}
// to
String[] destsArray = mDestList.toArray(new String[mDestList.size()]);
EncodedStringValue[] encodedNumbers = EncodedStringValue.encodeStrings(destsArray);
if (encodedNumbers != null) {
req.setTo(encodedNumbers);
}
// date
req.setDate(System.currentTimeMillis() / 1000);
// body
PduBody body = new PduBody();
// message text
final int size = addMessagePart(body, true/* add text smil */);
req.setBody(body);
// message size
req.setMessageSize(size);
// message class
req.setMessageClass(PduHeaders.MESSAGE_CLASS_PERSONAL_STR.getBytes());
// expiry
req.setExpiry(DEFAULT_EXPIRY_TIME);
try {
// priority
req.setPriority(DEFAULT_PRIORITY);
// delivery report
req.setDeliveryReport(PduHeaders.VALUE_NO);
// read report
req.setReadReport(PduHeaders.VALUE_NO);
} catch (InvalidHeaderValueException e) {}
return new PduComposer(mContext, req).make();
}
private String getSimNumber() {
TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager.getLine1Number();
}
private int addMessagePart(PduBody pb, boolean addTextSmil) {
PduPart part = new PduPart();
part.setCharset(CharacterSets.UTF_8);
part.setContentType(ContentType.TEXT_PLAIN.getBytes());
part.setContentLocation(TEXT_PART_FILENAME.getBytes());
int index = TEXT_PART_FILENAME.lastIndexOf(".");
String contentId = (index == -1) ? TEXT_PART_FILENAME : TEXT_PART_FILENAME.substring(0, index);
part.setContentId(contentId.getBytes());
part.setData(mMessage.getBytes());
pb.addPart(part);
if (addTextSmil) {
String smil = String.format(sSmilText, TEXT_PART_FILENAME);
addSmilPart(pb, smil);
}
return part.getData().length;
}
private void addSmilPart(PduBody pb, String smil) {
PduPart smilPart = new PduPart();
smilPart.setContentId("smil".getBytes());
smilPart.setContentType(ContentType.APP_SMIL.getBytes());
smilPart.setContentLocation("smil.xml".getBytes());
smilPart.setData(smil.getBytes());
pb.addPart(0, smilPart);
}
Relevant parts of my manifest
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Relevant instance variables
private final long DEFAULT_EXPIRY_TIME = 7 * 24 * 60 * 60;
private final String TEXT_PART_FILENAME = "text_0.txt";
private final int DEFAULT_PRIORITY = PduHeaders.PRIORITY_NORMAL;
private String mMessage;
private ArrayList<String> mDestList;
private Context mContext;
private static final String sSmilText =
"<smil>" +
"<head>" +
"<layout>" +
"<root-layout/>" +
"<region height=\"100%%\" id=\"Text\" left=\"0%%\" top=\"0%%\" width=\"100%%\"/>" +
"</layout>" +
"</head>" +
"<body>" +
"<par dur=\"8000ms\">" +
"<text src=\"%s\" region=\"Text\"/>" +
"</par>" +
"</body>" +
"</smil>";
I already do input checks, so by the time sendMMS() is called, my message and destList are not null.
The flow should be as such:
Create the Mms send-request - new SendReq() and config its date, body, to, etc.
Create the Mms body - new PduBody().
Create Parts via new PduPart() for each attachment, and add to the body: body.addPart(pdu)
Add the body to the request - req.setBody(body)
Convert the send-request to a byte[] ready to be sent by calling new PduComposer(context, mySendReq).make() - note that you'll need to copy lots of code from Android's source code to get the PduComposer class.
Now's the interesting part - you save the byte[] to a local file accessible to your app only, and add ContentProvider class that allows other apps to request access to your file, this is MmsFileProvider class in the sample app, don't forget to declare your provider in your manifest file.
Now, when you call the SmsManager.sendMultimediaMessage api, your file provider will wake up to serve the file containing the pdu bytes to the system SmsManager that will read it and send it on the wire.
Having that said, this API is only working for me on some devices (e.g. Nexuses), but not on some others (e.g. HTC One).
See my SO question here:
SmsManager MMS APIs on HTC/LG

Show Download Manager progress inside activity

I used Download Manager class inside my activity to perform downloads; it works fine and my next task is to show the same progress percentage inside my activity. I am not sure how to do it.
My code so far
public class DownloadSampleBook extends Activity{
private long enqueue;
private DownloadManager dm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample_download);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
view.setImageURI(Uri.parse(uriString));
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(
Uri.parse("http://abc.com/a.png"));
enqueue = dm.enqueue(request);
}
public void showDownload(View view) {
Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
}
Is there any method that give the progress download percentage?
If you are looking for a decent way to determine when to query the DownloadManager for progress updates, consider registering a ContentObserver for the uri content://downloads/my_downloads
Example:
DownloadManager manager = (DownloadManager) getSystemService( Context.DOWNLOAD_SERVICE );
manager.enqueue( myRequest );
Uri myDownloads = Uri.parse( "content://downloads/my_downloads" );
getContentResolver().registerContentObserver( myDownloads, true, new DownloadObserver() );
...
public static class DownloadObserver extends ContentObserver {
#Override
public void onChange( boolean selfChange, Uri uri ) {
Log.d( "DownloadObserver", "Download " + uri + " updated" );
}
This yields the following output as each chunk of the long running download is received
D/DownloadObserver(15584): Download content://downloads/my_downloads/437 updated
D/DownloadObserver(15584): Download content://downloads/my_downloads/437 updated
D/DownloadObserver(15584): Download content://downloads/my_downloads/437 updated
D/DownloadObserver(15584): Download content://downloads/my_downloads/437 updated
where '437' is the ID of your download.
Note that this follows the content URI defined in the class android.provider.Downloads which appears to be hidden in the framework and may not work consistently on all devices. (https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/provider/Downloads.java#89)
You can query the number of bytes downloaded so far, and the total number of bytes that need to be downloaded, using the query method, in much the same way as you have queried the status in your example code. Once you have those values, it's fairly easy to calculate the progress as a percentage.
There doesn't appear to be any way for you to be notified when new data is received, so it would be up to you to poll the download manager at some regular interval to determine the current status of any download that you want to monitor.
Query query = new Query();
query.setfilterById(downloadId);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int sizeIndex = c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
int downloadedIndex = c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
long size = c.getInt(sizeIndex);
long downloaded = c.getInt(downloadedIndex);
double progress = 0.0;
if (size != -1) progress = downloaded*100.0/size;
// At this point you have the progress as a percentage.
}
Note that the total size will initially be -1 and will only be filled in once the download starts. So in the sample code above I've checked for -1 and set the progress to 0 if the size is not yet set.
However, you may find in some cases that the total size is never returned (for example, in an HTTP chunked transfer, there will be no Content-Length header from which the size can be determined). If you need to support that kind of server, you should probably provide some kind of indication to the user that the download is progressing and not just a progress bar that is stuck at zero.
I had a requirement of tracking download of multiple files. After a lot of thinking and experimenting, I came up with the following code:
private void startDownloadThread(final List<DownloadFile> list) {
// Initializing the broadcast receiver ...
mBroadCastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mFinishedFilesFromNotif.add(intent.getExtras()
.getLong(DownloadManager.EXTRA_DOWNLOAD_ID));
}
};
IntentFilter intentFilter = new IntentFilter(
"android.intent.action.DOWNLOAD_COMPLETE");
DownloadProgressUIFragment.this.getActivity().registerReceiver(mBroadCastReceiver,
intentFilter);
// initializing the download manager instance ....
mDownloadManager = (DownloadManager) getActivity()
.getSystemService(Context.DOWNLOAD_SERVICE);
// adding files to the download manager list ...
for(DownloadFile f: list) {
mDownloadIds.add(FileUtils.addFileForDownloadInBkg(getApplicationContext(),
f.getUrl(),
f.getPath()));
}
// starting the thread to track the progress of the download ..
mProgressThread = new Thread(new Runnable() {
#Override
public void run() {
// Preparing the query for the download manager ...
DownloadManager.Query q = new DownloadManager.Query();
long[] ids = new long[mDownloadIds.size()];
final List<Long> idsArrList= new ArrayList<>();
int i = 0;
for (Long id: mDownloadIds) {
ids[i++] = id;
idsArrList.add(id);
}
q.setFilterById(ids);
// getting the total size of the data ...
Cursor c;
while(true) {
// check if the downloads are already completed ...
// Here I have created a set of download ids from download manager to keep
// track of all the files that are dowloaded, which I populate by creating
//
if(mFinishedFilesFromNotif.containsAll(idsArrList)) {
isDownloadSuccess = true;
// TODO - Take appropriate action. Download is finished successfully
return;
}
// start iterating and noting progress ..
c = mDownloadManager.query(q);
if(c != null) {
int filesDownloaded = 0;
float fileFracs = 0f; // this stores the fraction of all the files in
// download
final int columnTotalSize = c.getColumnIndex
(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
final int columnStatus = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
//final int columnId = c.getColumnIndex(DownloadManager.COLUMN_ID);
final int columnDwnldSoFar =
c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
while (c.moveToNext()) {
// checking the progress ..
if(c.getInt(columnStatus) == DownloadManager.STATUS_SUCCESSFUL) {
filesDownloaded++;
}
// If the file is partially downloaded, take its fraction ..
else if(c.getInt(columnTotalSize) > 0) {
fileFracs += ((c.getInt(columnDwnldSoFar) * 1.0f) /
c.getInt(columnTotalSize));
} else if(c.getInt(columnStatus) == DownloadManager.STATUS_FAILED) {
// TODO - Take appropriate action. Error in downloading one of the
// files.
return;
}
}
c.close();
// calculate the progress to show ...
float progress = (filesDownloaded + fileFracs)/ids.length;
// setting the progress text and bar...
final int percentage = Math.round(progress * 100.0f);
final String txt = "Loading ... " + percentage + "%";
// Show the progress appropriately ...
}
}
}
});
mProgressThread.start();
}
And the function to enqueue to files are:
public static long addFileForDownloadInBkg(Context context, String url, String savePath) {
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
request.setDestinationUri(Uri.fromFile(new File(savePath)));
final DownloadManager m = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
return m.enqueue(request);
}
Basically, I receive a notification individually for each of the files whose download has been finished and then add them to a set which is basically the set which helps me decide if all the downloads have been finished or not. I track the the progress based on the number of files and the fraction of each being complete. I hope this helps.

Categories

Resources