1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package libcore.net.event; 18 19 import java.util.List; 20 import java.util.concurrent.CopyOnWriteArrayList; 21 22 /** 23 * A singleton used to dispatch network events to registered listeners. 24 */ 25 public class NetworkEventDispatcher { 26 27 private static final NetworkEventDispatcher instance = new NetworkEventDispatcher(); 28 29 private final List<NetworkEventListener> listeners = 30 new CopyOnWriteArrayList<NetworkEventListener>(); 31 32 /** 33 * Returns the shared {@link NetworkEventDispatcher} instance. 34 */ getInstance()35 public static NetworkEventDispatcher getInstance() { 36 return instance; 37 } 38 39 /** Visible for testing. Use {@link #getInstance()} instead. */ NetworkEventDispatcher()40 protected NetworkEventDispatcher() { 41 } 42 43 /** 44 * Registers a listener to be notified when network events occur. 45 * It can be deregistered using {@link #removeListener(NetworkEventListener)} 46 */ addListener(NetworkEventListener toAdd)47 public void addListener(NetworkEventListener toAdd) { 48 if (toAdd == null) { 49 throw new NullPointerException("toAdd == null"); 50 } 51 listeners.add(toAdd); 52 } 53 54 /** 55 * De-registers a listener previously added with {@link #addListener(NetworkEventListener)}. If 56 * the listener was not previously registered this is a no-op. 57 */ removeListener(NetworkEventListener toRemove)58 public void removeListener(NetworkEventListener toRemove) { 59 for (NetworkEventListener listener : listeners) { 60 if (listener == toRemove) { 61 listeners.remove(listener); 62 return; 63 } 64 } 65 } 66 67 /** 68 * Notifies registered listeners of a network configuration change. 69 */ onNetworkConfigurationChanged()70 public void onNetworkConfigurationChanged() { 71 for (NetworkEventListener listener : listeners) { 72 try { 73 listener.onNetworkConfigurationChanged(); 74 } catch (RuntimeException e) { 75 System.logI("Exception thrown during network event propagation", e); 76 } 77 } 78 } 79 } 80