ConnectivityManager.NetworkCallback() -> onAvailable(Network network) method is not triggered when device connects to a internal wifi network

sonu769 picture sonu769 · Feb 5, 2019 · Viewed 7.4k times · Source

I am trying to send telementary data to App Center on out internal wifi network but it is not sending on this network but it does on any external network. When debugging found that Method onAvailable() is not called when device is connected to internal wifi but it does get called when connected to any external wifi.

Below code is from App Center SDK :
appcenter\utils\NetworkStateHelper.javaNetworkStateHelper.java. Class NetworkStateHelper -> Method reopen() --> public void onAvailable(Network network) method

Sample Code:

private ConnectivityManager.NetworkCallback mNetworkCallback = new ConnectivityManager.NetworkCallback() 
{

    @Override
    public void onAvailable(Network network) {
        onNetworkAvailable(network);
    }

    @Override
    public void onLost(Network network) {
        onNetworkLost(network);
    }
};

It should call the onAvailable method when connected to an internal wifi network.

Answer

Maksim Novikov picture Maksim Novikov · Feb 5, 2019

As written in the android docs :

Apps targeting Android 7.0 (API level 24) and higher do not receive CONNECTIVITY_ACTION broadcasts if they declare the broadcast receiver in their manifest. Apps will still receive CONNECTIVITY_ACTION broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.

This means if your target api is higher than 24 you need to register broadcast receiver when your activity starts.

in you Activity onCreate()

IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectivityReceiver, intentFilter);

declare the broadcast:

private BroadcastReceiver connectivityReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      //check state here....
    }
  };