Pausing service until internet connection can be e

2019-03-29 07:15发布

问题:

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?

回答1:

but this feels vulgar

Indeed :D

  1. Your receiver wakes your wakeful intent service (probably a simple intent service would do, as the phone does not sleep while booting AFAIK)
  2. service registers a receiver for connectivity
  3. service waits on a CountDownLatch
  4. 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)



回答2:

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