简体   繁体   中英

Detect 3G or Wifi Network restoration

Is it possible to implement a PhoneStateListener(or any other mechanism) to detect when either the 3G or Wifi network connection is restored ?

I see both LISTEN_DATA_CONNECTION_STATE and LISTEN_DATA_ACTIVITY say (cellular) in the API's summary. Does it mean 3G only ?

Thanks

Better approach would be to use android.net.ConnectivityManager class. Register the receiver and monitor broadcasts.

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)) {
                // Handle connected case
            }
        } else {
            if ((aNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
                || (aNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI)) {
                // Handle disconnected case
            }
        }
    }
}

private synchronized void startMonitoringConnection() {
    IntentFilter aFilter = new IntentFilter(
        ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(mConnectionReceiver, aFilter);
}
private synchronized void stopMonitoringConnection() {
    unregisterReceiver(mConnectionReceiver);
}

where

mConnectionReceiver = new ConnectionMonitor();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM