Pausing service until internet connection can be established

自古美人都是妖i 提交于 2019-12-03 15:16:49
Mr_and_Mrs_D

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)

znat

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!