Skip to content

Question: How to use Android Framework features that rely on Activities, BroadcastReceivers, etc #104

Open
@balazsgerlei

Description

@balazsgerlei

I proposed this question originally on Twitter to @android10 and he was right that an issue is better. I implemented similar architectures in apps but frequently wondered what is the best way to integrate features provided by the Android Framework that rely heavily on Activities, Fragments, BroadcastReceivers, etc. (I kind of just hacked these into it if I had to TBH)

I would like to ask this question generally about any such features, but in order to talk about this easier, I will show an example: DownloadManager

It's nice functionality that is provided by the system and while of course downloading something can be done via Retrofit or some other implementation as well, DownloadManager handles the UI feedback (via Notifications), errors and retries, reboots, etc. so it has different pros and cons that might be more fitting to an app. And think about the (storage) permission requirements, they are compeletely different if you use your own logic vs DownloadManager.

Instinct may suggest making this a Repository as well, but DownloadManager relies on Broadcasts to notify the app about the download result for example, so it cannot really be put in a Repository. An example BroadcastReceiver to be notified about the result and get the path for the downloaded file:

private class DownloadCompletedBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        final Bundle extras = intent.getExtras();
        if (extras != null) {
            final long downloadId = extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            final DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
            try (Cursor c = downloadManager.query(query)) {
                if (c.moveToFirst()) {
                    final int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
                    if (status == DownloadManager.STATUS_SUCCESSFUL) {
                        final String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                        final String filePath = Uri.parse(uriString).getPath(); // This is the path of the downloaded File
                    }
                }
            } catch (Exception ignored) {}
        }
    }

};

So how would be the best way to integrate such features with this architecture?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions