Reputation: 5338
I have a broadcast receiver that gets fired whenever a download finishes in the system. What i want to do is to send the result of this receiver to my fragment where i update the views. Currently i use this approach.
public class DownloadCompleteReceiver extends BroadcastReceiver {
public interface DownloadListener {
public void downloadCompleted(int appId);
}
private static List<DownloadListener> downloadListeners = new LinkedList<>();
public static void registerDownloadListener(DownloadListener downloadListener){
downloadListeners.add(downloadListener);
}
public static void unregisterDownloadListener(DownloadListener downloadListener){
downloadListeners.remove(downloadListener);
}
@Override
public void onReceive(Context context, Intent intent) {
//whatever calculation needed to be done.
for(DownloadListener listener: downloadListeners)
if(listener != null)
listener.downloadCompleted(appId);
}
}
and in my fragment onStart method i do this.
DownloadCompleteReceiver.registerDownloadListener(this);
and in onStop method
DownloadCompleteReceiver.unregisterDownloadListener(this);
then i implement the interface and i have the result! It's a straightforward solution that works perfectly fine. I wonder is something wrong with my code? do i miss something?! I spent hours searching on the matter but no one uses this approach! is there a reason why?
BTW i need to define my receiver in separate class because i want it to be fired even if my application is closed so inner classing my receiver is not an option here.
Upvotes: 2
Views: 2036
Reputation: 3417
There is nothing wrong with this approach.
First of all your receiver registered in onStart and Unregistered in onStop method.
So if your activity is running(i mean not stopped) and you remove or replace your fragment.then you will never be able to unregister your receiver.
So if you only uses this listeners for this fragment only you should register and unregister you receiver in onAttach and onDetach of fragment.
Hope it will help.Thanks.
Upvotes: 0
Reputation: 12541
I don't see anything wrong with this approach, I used the same approach for my project.
If you are asking whether there are alternative ways of doing it, you can check out event-based libraries for asynchronous communication:
There have been questions comparing event-based framework with Android's LocalBroadcast also: Otto vs LocalBroadcast:
Upvotes: 1