Question

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

Was it helpful?

Solution

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top