Using Broadcast Receiver with Downloadmanager

Asked

Viewed 414 times

2

I’m learning to make use of the DownloadManager with BroadcastReceiver to know when the download is completed.

The problem: let’s assume that I will download 2 Pdfs on a page, I record 2 Receiver, that is, one for each PDF, then I put each of them in the download queue (see the call dm.enqueue). What happens is that for every completed download (status == 8) I get 2 times this notification.

In the application when the page has only 2 Pdfs to download the dm.enqueue(request); is called only twice as expected.

I thought: the completed download notification should not be sent only once for each file?

    DownloadManager.Request request = new DownloadManager.Request(uri);
    request.setDescription(getString(R.string.download_description));
    request.setTitle(getString(R.string.download_title));
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request
            .VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalPublicDir(Environment
            .DIRECTORY_DOWNLOADS, uri.getLastPathSegment());
    dm = (DownloadManager) getSystemService(Context
            .DOWNLOAD_SERVICE);
    BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context ctxt, Intent intent) {

            Log.d(TAG, "onReceive called");

            // http://stackoverflow.com/a/13322285/3697611
            Bundle extras = intent.getExtras();
            DownloadManager.Query q = new DownloadManager.Query();
            q.setFilterById(extras.getLong(DownloadManager
                    .EXTRA_DOWNLOAD_ID));
            Cursor c = dm.query(q);
            if (c.moveToFirst()) {
                int status = c.getInt(c.getColumnIndex
                        (DownloadManager.COLUMN_STATUS));

                // se estiver completo
                if (status == DownloadManager.STATUS_SUCCESSFUL) {
                    String uri = c.getString(c.getColumnIndex
                            (DownloadManager.COLUMN_URI));
                    String local_uri = c.getString(c.getColumnIndex
                            (DownloadManager.COLUMN_LOCAL_URI));

                    //TODO: bug, estas mensagens estão aparecendo 2
                    // vezes para cada download
                    display(getString(R.string.completed) + uri);
                    display(getString(R.string.saved) + local_uri);

                    try {

                        // quando completar o download devemos
                        // pegar o texto
                        getText(new File(new URI(local_uri)));

                    } catch (URISyntaxException e) {
                        printStackTrace(e);
                    }
                }

            }

        }
    };
    registerReceiver(receiver, new IntentFilter(DownloadManager
            .ACTION_DOWNLOAD_COMPLETE));
    receivers.add(receiver);
    dm.enqueue(request);

The complete code is here.

P.S.: this is just a very simple application I did to develop my knowledge about Android, currently it searches Pdfs on the page where publish the official journal of the municipality of the city where I live.

Note: the app was tested on an Alcatel Pixi 4'6 with Android 5.1.

Debugging

When I put a logd I see messages like this:

09-04 15:10:28.395 30024-30252/com.example.android.officialdiary D/com.example.android.officialdiary.MainActivity: download: dm.enqueue register a request
09-04 15:10:28.422 30024-30252/com.example.android.officialdiary D/com.example.android.officialdiary.MainActivity: download: dm.enqueue register a request
09-04 15:10:33.288 30024-30024/com.example.android.officialdiary D/com.example.android.officialdiary.MainActivity: download: onReceive called
09-04 15:10:33.312 30024-30024/com.example.android.officialdiary D/com.example.android.officialdiary.MainActivity: download: onReceive called
09-04 15:10:34.593 30024-30024/com.example.android.officialdiary D/com.example.android.officialdiary.MainActivity: download: onReceive called
09-04 15:10:34.609 30024-30024/com.example.android.officialdiary D/com.example.android.officialdiary.MainActivity: download: onReceive called

We noticed that two were registered requests (at that moment has 2 Pdfs in the portal), but for each of them the onReceive was triggered twice (total gave 4/2 = 2).

Note: if you want to test the code faster just start the debugging section of Android Studio and when the App starts uncheck "Extract text" and check "Clear data" (will erase downloaded Pdfs and download again but will not extract text from Pdfs).

1 answer

1

The Broadcastreceiver is being recorded in the method download().

Each time the method download() is called the Broadcastreceiver is registered.

When the download finish the Broadcastreceiver will be called the times it was registered.

It shall establish and register the Broadcastreceiver only once in the method onCreate().

Note: I see you’re using the builder of Activity to create the array of recievers, don’t use it, do it on onCreate().

  • thanks for the @ramaral comment, see the "debugging" section and tell me what you think

  • changed the code, stopped using the constructor to inialize the receivers array, thanks @ramaral

  • 1

    You have to take into account that method onDestroy() may not be called and in that case Broadcastreceiver is not "unregistered". Uninstall the application and retry.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.