I've created an IntentService
for downloading a file using Android's DownloadManager. Following is my Class:
public class DownloadService extends IntentService {
public DownloadService() {
super("name");
}
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
function();
}
};
@Override
protected void onHandleIntent(Intent intent) {
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Utility.download(someURL);
}
}
I've this entry in manifest:
<service
android:name=".services.DownloadService"
android:enabled="true" >
</service>
The code inside BroadcastReceiver(function())
is never executing even if the file is downloaded. I also tried doing the same thing in Service
instead of IntentService
, it worked.
How can I make BroadcastReceiver work inside IntentService?
Avoid calling
registerReceiver
method using IntentService's context.Once your IntentService#onHandleIntent method returns, the Service#stopSelf(int) method will be called. All the not-yet-unregistered receivers will be considered as leaked. The framework even warns you about that:
And of course, none of your leaked broadcast receivers will receive notifications afterwards.
If you still want to register the broadcast receiver within IntentService#onHandleIntent method, use (for example) Application's context for that.
Note however, that you'll have to add logic that unregisters each such receiver instance once you finish with it.