Search code examples
androidhttpdownloadandroid-2.3-gingerbreadandroid-download-manager

Download file with DownloadManager on API Level 9+ and fall back to AsyncTask <9


I have a service class which should handle downloading of a particular file.

A first version was written using AsyncTask. Since it's a large file and over HTTPS it would be great to use DownloadManager, so I've refactored the service to use the DownloadManager service.

How can I build a service class myself which uses DownloadManager when supported (API-Level >9) and falls back to the AsyncTask-solution when <9?


Solution

  • Answering my own question, here's what I did:

    1. Build an abstract service base class e.g. DownloadService
    2. Extend to concrete subclasses e.g. AsyncTaskDownloadService and DownloadManagerDownloadService
    3. When creating the service, use feature-detection instead of build levels (it's more elegant to me) this looks like the following:

      Activity activity = getActivity();
      Object downloadService = activity.getSystemService(Context.DOWNLOAD_SERVICE);
      Class serviceClass = AsyncTaskDownloadService.class;
      if (downloadService != null) {
          serviceClass = DownloadManagerDownloadService.class;
      }
      Intent serviceIntent = new Intent(activity, serviceClass);
      activity.startService(serviceIntent);
      

    This will use the older approach when on API level <9 and use the DownloadManager approach when >=9.