I have a service that runs upon boot completion. This service requires internet connectivity. What's the best practice for waiting for the device to connect to the internet? Mobile of wifi doesn't really matter.
My current solution involves a while loop that just checks ConnectivityManager until one of the networks becomes available, but this feels vulgar.
Is there a better way to do this?
but this feels vulgar
Indeed :D
- Your receiver wakes your wakeful intent service (probably a simple intent service would do, as the phone does not sleep while booting AFAIK)
- service registers a receiver for connectivity
- service waits on a CountDownLatch
- the receiver wakes the service up when the wifi is connected
Skeleton code : https://stackoverflow.com/a/19968708/281545 - your case is simpler as you do not have to wake the wifi, hold wifi locks etc. Otherwise (including the case this takes long and radios/CPU sleep - in which case a simple intent service won't do) between 2 and 3 you would need to :
2a. service acquires a wifi lock
2b. service calls reconnect()
, reassociate()
and whatever is needed (this may be device specific)
You could use a BroadcastReceiver:
private class ConnectionMonitor extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION))
return;
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
NetworkInfo aNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (!noConnectivity) {
if ((aNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
|| (aNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI)) {
// start your service stuff here
}
} else {
if ((aNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
|| (aNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI)) {
// stop your service stuff here
}
}
}
}
Then, you instantiate somewhere in your code:
ConnectionMonitor connectionMonitor = new ConnectionMonitor();
registerReceiver(connectionMonitor, intentFilter);
Note: this code comes from Detect 3G or Wifi Network restoration