BroadcastReceiver receives multiple identical messages for one event

后端 未结 6 1390
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 11:10

I registered a receiver that listens to network events:



        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 12:06

    My concern with the approach proposed by Aleksander is that it doesn't consider network changes of the same type, e.g. from one WiFi network to another.

    I'm proposing to compare the extraInfo of the active network, which contains the network name, e.g. WiFi SSID or mobile network name like VZW

     String currentNetworkName = "";
    
     ConnectivityManager connectivityManager =
                ((ConnectivityManager) context.getSystemService(
                        Context.CONNECTIVITY_SERVICE));
    
        NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
        boolean connected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        if (connected) {
            // prevent duplicate connect broadcasts
            String extraInfo = activeNetwork.getExtraInfo();
            if(! currentNetworkName.equals(extraInfo)) {
                // to do: handle network changes
                currentNetworkName = extraInfo;
            }
        } else {
            Log.d(TAG, "is not connected");
            isConnected = false;
            currentNetworkName = "";
        }
    

提交回复
热议问题