I have a function which I need to run when my app gets some data from remote server. HTTPRequest
requires some time to execute, so when I get necessary data I send broadcast
Intent i = new Intent();
i.setAction(Receiver.BROADCAST_INITIALIZED);
activity.sendBroadcast(i);
My receiver:
public class Receiver extends BroadcastReceiver{
public static final String BROADCAST_INITIALIZED = "UNIQUE_ID";
public Receiver() {}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BROADCAST_INITIALIZED)) {
Log.i("TAG", "RECEIVER BROADCAST_INITIALIZED");
context.unregisterReceiver(this);
}
}
}
Everything works as expected until I disable mobile data and WiFi. In this case activity.sendBroadcast(i);
does not trigger. I wonder why?
I use simple function to check connection:
static boolean isNetworkAvailable(final Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null
&& connectivityManager.getActiveNetworkInfo().isConnected();
}
and place it in timer (timer.scheduleAtFixedRate
). When network is becoming available I execute HTTPRequest and get data after that I send broadcast and even then it doen't work!
Does sendbroadcast
function work only when network is available?
UPDATE I found out the problem. It was my mistake. When I register my receivers I check network availability too and if it is not available I just skip registration.
if(!Utils.isNetworkAvailable(activity)) return; //The root of my problem!!!
Receiver receiver = new Receiver(new Callable<Void>() {
@Override
public Void call() throws Exception {
func.call();
return null;
}
});
activity.registerReceiver(receiver, new IntentFilter(Receiver.BROADCAST_INITIALIZED));