9

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.

ankuranurag2
  • 2,300
  • 15
  • 30
S Gupta
  • 139
  • 1
  • 3
  • 11

3 Answers3

12

You have to restrict the network type to Wifi.

1. Build the NetworkRequest:

val networkRequest = getNetworkRequest()

private fun getNetworkRequest(): NetworkRequest {
    return NetworkRequest.Builder()
        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)    //here!!
        .build()
}

2. Build the NetworkCallback:

val networkCallback = getNetworkCallBack()

private fun getNetworkCallBack(): ConnectivityManager.NetworkCallback {
    return object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) {    //when Wifi is on
            super.onAvailable(network)

            Toast.makeText(requireContext(), "Wifi is on!", Toast.LENGTH_SHORT).show()
        }

        override fun onLost(network: Network) {    //when Wifi 【turns off】
            super.onLost(network)

            Toast.makeText(requireContext(), "Wifi turns off!", Toast.LENGTH_SHORT).show()
        }
    }
}

3. Register and Unregister:

fun getConnectivityManager() = requireContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

override fun onResume() {    //start monitoring when in the foreground
    super.onResume()

    getConnectivityManager().registerNetworkCallback(networkRequest, networkCallback)
}

override fun onPause() {    //stop monitoring when not fully visible
    super.onPause()

    getConnectivityManager().unregisterNetworkCallback(networkCallback)
}

4. Don't forget the permission:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Demo: https://youtu.be/RPRcGbuB6eI

Sam Chen
  • 7,597
  • 2
  • 40
  • 73
2

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....
    }
  };
Maksim Novikov
  • 835
  • 6
  • 18
0

I have a problem, i would like refresh (Force Refresh) because public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) not change speedly.

connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkRequest networkRequest = new NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
                .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
                .build();

        wifiBande1Infos = new JSONObject();
        wifiBande2Infos = new JSONObject();

        NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback(ConnectivityManager.NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) {
                    @Override
                    public void onAvailable(Network network) {

                    }


                    @Override
                    public void onLost(Network network) {

                    }

                    @Override
                    public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {
                    }

                    @Override
                    public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
                        super.onCapabilitiesChanged(network, networkCapabilities);
                        executor.execute(() -> {

                            Network activeNetwork = connectivityManager.getActiveNetwork();
                            LinkProperties linkProperties = connectivityManager.getLinkProperties(activeNetwork);

                            linkProperties = connectivityManager.getLinkProperties(network);
                            interfaceName = linkProperties.getInterfaceName();

                            WifiInfo wifiInfo = (WifiInfo) networkCapabilities.getTransportInfo();

                            if (wifiInfo != null) {
                                String ssid = wifiInfo.getSSID();

                                try {

                                    if (interfaceName.equals("wlan0")) {

                                        JSONObject ssidEntry = new JSONObject();
                                        ssidEntry.put("getRssi", String.valueOf(wifiInfo.getRssi()));
                                        ssidEntry.put("getRssi2", String.valueOf(networkCapabilities.getSignalStrength()));
                                        
                                        JSONArray ssidEntryArray = new JSONArray();
                                        ssidEntryArray.put(ssidEntry);

                                        wifiBande1Infos.put(interfaceName, ssidEntryArray);
                                    } else if (interfaceName.equals("wlan1")) {

                                        
                                        JSONObject ssidEntry = new JSONObject();
                                        
                                        ssidEntry.put("getRssi", String.valueOf(wifiInfo.getRssi()));
                                        ssidEntry.put("getRssi2", String.valueOf(networkCapabilities.getSignalStrength()));
                                        
                                        JSONArray ssidEntryArray = new JSONArray();
                                        ssidEntryArray.put(ssidEntry);

                                        wifiBande2Infos.put(interfaceName, ssidEntryArray);
                                    }

                                    refreshInfosWifi();

                                } catch (JSONException e) {
                                    Log.e(TAG, "Error Connection 152", e);
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                };


        connectivityManager.registerNetworkCallback(networkRequest, networkCallback); 
        connectivityManager.requestNetwork(networkRequest, networkCallback); 


scheduler = Executors.newScheduledThreadPool(1);
    scheduler.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {

            try {
                updateRSSI();
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }

        }
    }, 0, 1, TimeUnit.SECONDS);



 private void updateRSSI() throws JSONException {

    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    int wlan0_rssi_old = wifiInfo.getRssi();

    //Log.d(TAG, "Refresh 2s : Rssi Wlan0 OLD : "+wlan0_rssi_old);

    if(!wifiBande1Infos.isNull("wlan0")) {
        JSONArray wifiBande1InfosArray = wifiBande1Infos.getJSONArray("wlan0");
        JSONObject wifiBande1InfosObj = wifiBande1InfosArray.getJSONObject(0);
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities((Network) wifiBande1InfosObj.get("IdNetworkMaster"));
        WifiInfo wifiInfoRefresh = (WifiInfo) networkCapabilities.getTransportInfo();

       

    }
    if(!wifiBande2Infos.isNull("wlan1")) {
        JSONArray wifiBande2InfosArray = wifiBande2Infos.getJSONArray("wlan1");
        JSONObject wifiBande2InfosObj = wifiBande2InfosArray.getJSONObject(0);
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities((Network) wifiBande2InfosObj.get("IdNetworkMaster"));
        WifiInfo wifiInfoRefresh = (WifiInfo) networkCapabilities.getTransportInfo();

      

    }


    runOnUiThread(new Runnable() {
                      @Override
                      public void run() {
                          TextView T_wifiRSSI_old_txt = findViewById(R.id.wifiRSSI_old_txt);
                          T_wifiRSSI_old_txt.setText(String.valueOf(wlan0_rssi_old)+" dBm");
                          ProgressBar P_wifiRSSI_old = findViewById(R.id.wifiRSSI_old);
                          P_wifiRSSI_old.setProgress(Integer.parseInt(String.valueOf(wlan0_rssi_old)));

                      }
                  });
}

As you can see above, I use the latest APIs >=33, anyway my application only works under 33.

The goal is to compare the RSSI refresh between :

  • the old method : WifiInfo wifiInfo = wifiManager.getConnectionInfo();
  • the new method : WifiInfo wifiInfoRefresh = (WifiInfo) networkCapabilities.getTransportInfo();

I see that the forced refresh works well with the old method. On the other hand, with the news, I can't update either onCapabilitiesChanged, or by fetching the value myself.

I must be doing it wrong, can you correct my mistakes?

I add to this a very strange effect of the new way, below -50 dBm there is no more updating for the 2 wlans. On the other hand, the old method goes well up to -1dbm. Unless there is a possibility to actually force the refresh via the new method.

Thank you in advance for anyone who can help me, I've been on it for several days... :)

  • This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/34300335) – RusArtM May 03 '23 at 03:36