BroadcastReceiver receives multiple identical messages for one event

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

I registered a receiver that listens to network events:



        
6条回答
  •  温柔的废话
    2020-12-02 11:56

    You can also cache in a static field the last handled connection type and check against the incomming broadcasts. This way you will only get one broadcast per connection type.

    When connection type gets changed it will obviously work. When device gets out of connection activeNetworkInfo will be null and currentType will be NO_CONNECTION_TYPE as in default case.

    public class ConnectivityReceiver extends BroadcastReceiver {
    
        /** The absence of a connection type. */
        private static final int NO_CONNECTION_TYPE = -1;
    
        /** The last processed network type. */
        private static int sLastType = NO_CONNECTION_TYPE;
    
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectivityManager = (ConnectivityManager)
                    context.getSystemService(Context.CONNECTIVITY_SERVICE);
    
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            final int currentType = activeNetworkInfo != null
                    ? activeNetworkInfo.getType() : NO_CONNECTION_TYPE;
    
            // Avoid handling multiple broadcasts for the same connection type
            if (sLastType != currentType) {
                if (activeNetworkInfo != null) {
                    boolean isConnectedOrConnecting = activeNetworkInfo.isConnectedOrConnecting();
                    boolean isWiFi = ConnectivityManager.TYPE_WIFI == currentType;
                    boolean isMobile = ConnectivityManager.TYPE_MOBILE == currentType;
    
                    // TODO Connected. Do your stuff!
                } else {
                    // TODO Disconnected. Do your stuff!
                }
    
                sLastType = currentType;
            }
    }
    

提交回复
热议问题