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

。_饼干妹妹 提交于 2020-01-03 18:03:40

问题


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.


回答1:


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....
    }
  };


来源:https://stackoverflow.com/questions/54527301/connectivitymanager-networkcallback-onavailablenetwork-network-method-is

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