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?
Answering my own question, here's what I did:
DownloadService
AsyncTaskDownloadService
and DownloadManagerDownloadService
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.