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.