RemoteCallbackList.java revision 7a1355950172b7a549820e9a2cd4a9b2099ec32f
1/* 2 * Copyright (C) 2008 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 17package android.os; 18 19import java.util.HashMap; 20 21/** 22 * Takes care of the grunt work of maintaining a list of remote interfaces, 23 * typically for the use of performing callbacks from a 24 * {@link android.app.Service} to its clients. In particular, this: 25 * 26 * <ul> 27 * <li> Keeps track of a set of registered {@link IInterface} callbacks, 28 * taking care to identify them through their underlying unique {@link IBinder} 29 * (by calling {@link IInterface#asBinder IInterface.asBinder()}. 30 * <li> Attaches a {@link IBinder.DeathRecipient IBinder.DeathRecipient} to 31 * each registered interface, so that it can be cleaned out of the list if its 32 * process goes away. 33 * <li> Performs locking of the underlying list of interfaces to deal with 34 * multithreaded incoming calls, and a thread-safe way to iterate over a 35 * snapshot of the list without holding its lock. 36 * </ul> 37 * 38 * <p>To use this class, simply create a single instance along with your 39 * service, and call its {@link #register} and {@link #unregister} methods 40 * as client register and unregister with your service. To call back on to 41 * the registered clients, use {@link #beginBroadcast}, 42 * {@link #getBroadcastItem}, and {@link #finishBroadcast}. 43 * 44 * <p>If a registered callback's process goes away, this class will take 45 * care of automatically removing it from the list. If you want to do 46 * additional work in this situation, you can create a subclass that 47 * implements the {@link #onCallbackDied} method. 48 */ 49public class RemoteCallbackList<E extends IInterface> { 50 /*package*/ HashMap<IBinder, Callback> mCallbacks 51 = new HashMap<IBinder, Callback>(); 52 private Object[] mActiveBroadcast; 53 private boolean mKilled = false; 54 55 private final class Callback implements IBinder.DeathRecipient { 56 final E mCallback; 57 final Object mCookie; 58 59 Callback(E callback, Object cookie) { 60 mCallback = callback; 61 mCookie = cookie; 62 } 63 64 public void binderDied() { 65 synchronized (mCallbacks) { 66 mCallbacks.remove(mCallback.asBinder()); 67 } 68 onCallbackDied(mCallback, mCookie); 69 } 70 } 71 72 /** 73 * Simple version of {@link RemoteCallbackList#register(E, Object)} 74 * that does not take a cookie object. 75 */ 76 public boolean register(E callback) { 77 return register(callback, null); 78 } 79 80 /** 81 * Add a new callback to the list. This callback will remain in the list 82 * until a corresponding call to {@link #unregister} or its hosting process 83 * goes away. If the callback was already registered (determined by 84 * checking to see if the {@link IInterface#asBinder callback.asBinder()} 85 * object is already in the list), then it will be left as-is. 86 * Registrations are not counted; a single call to {@link #unregister} 87 * will remove a callback after any number calls to register it. 88 * 89 * @param callback The callback interface to be added to the list. Must 90 * not be null -- passing null here will cause a NullPointerException. 91 * Most services will want to check for null before calling this with 92 * an object given from a client, so that clients can't crash the 93 * service with bad data. 94 * 95 * @param cookie Optional additional data to be associated with this 96 * callback. 97 * 98 * @return Returns true if the callback was successfully added to the list. 99 * Returns false if it was not added, either because {@link #kill} had 100 * previously been called or the callback's process has gone away. 101 * 102 * @see #unregister 103 * @see #kill 104 * @see #onCallbackDied 105 */ 106 public boolean register(E callback, Object cookie) { 107 synchronized (mCallbacks) { 108 if (mKilled) { 109 return false; 110 } 111 IBinder binder = callback.asBinder(); 112 try { 113 Callback cb = new Callback(callback, cookie); 114 binder.linkToDeath(cb, 0); 115 mCallbacks.put(binder, cb); 116 return true; 117 } catch (RemoteException e) { 118 return false; 119 } 120 } 121 } 122 123 /** 124 * Remove from the list a callback that was previously added with 125 * {@link #register}. This uses the 126 * {@link IInterface#asBinder callback.asBinder()} object to correctly 127 * find the previous registration. 128 * Registrations are not counted; a single unregister call will remove 129 * a callback after any number calls to {@link #register} for it. 130 * 131 * @param callback The callback to be removed from the list. Passing 132 * null here will cause a NullPointerException, so you will generally want 133 * to check for null before calling. 134 * 135 * @return Returns true if the callback was found and unregistered. Returns 136 * false if the given callback was not found on the list. 137 * 138 * @see #register 139 */ 140 public boolean unregister(E callback) { 141 synchronized (mCallbacks) { 142 Callback cb = mCallbacks.remove(callback.asBinder()); 143 if (cb != null) { 144 cb.mCallback.asBinder().unlinkToDeath(cb, 0); 145 return true; 146 } 147 return false; 148 } 149 } 150 151 /** 152 * Disable this callback list. All registered callbacks are unregistered, 153 * and the list is disabled so that future calls to {@link #register} will 154 * fail. This should be used when a Service is stopping, to prevent clients 155 * from registering callbacks after it is stopped. 156 * 157 * @see #register 158 */ 159 public void kill() { 160 synchronized (mCallbacks) { 161 for (Callback cb : mCallbacks.values()) { 162 cb.mCallback.asBinder().unlinkToDeath(cb, 0); 163 } 164 mCallbacks.clear(); 165 mKilled = true; 166 } 167 } 168 169 /** 170 * Old version of {@link #onCallbackDied(E, Object)} that 171 * does not provide a cookie. 172 */ 173 public void onCallbackDied(E callback) { 174 } 175 176 /** 177 * Called when the process hosting a callback in the list has gone away. 178 * The default implementation calls {@link #onCallbackDied(E)} 179 * for backwards compatibility. 180 * 181 * @param callback The callback whose process has died. Note that, since 182 * its process has died, you can not make any calls on to this interface. 183 * You can, however, retrieve its IBinder and compare it with another 184 * IBinder to see if it is the same object. 185 * @param cookie The cookie object original provided to 186 * {@link #register(E, Object)}. 187 * 188 * @see #register 189 */ 190 public void onCallbackDied(E callback, Object cookie) { 191 onCallbackDied(callback); 192 } 193 194 /** 195 * Prepare to start making calls to the currently registered callbacks. 196 * This creates a copy of the callback list, which you can retrieve items 197 * from using {@link #getBroadcastItem}. Note that only one broadcast can 198 * be active at a time, so you must be sure to always call this from the 199 * same thread (usually by scheduling with {@link Handler} or 200 * do your own synchronization. You must call {@link #finishBroadcast} 201 * when done. 202 * 203 * <p>A typical loop delivering a broadcast looks like this: 204 * 205 * <pre> 206 * final int N = callbacks.beginBroadcast(); 207 * for (int i=0; i<N; i++) { 208 * try { 209 * callbacks.getBroadcastItem(i).somethingHappened(); 210 * } catch (RemoteException e) { 211 * // The RemoteCallbackList will take care of removing 212 * // the dead object for us. 213 * } 214 * } 215 * callbacks.finishBroadcast();</pre> 216 * 217 * @return Returns the number of callbacks in the broadcast, to be used 218 * with {@link #getBroadcastItem} to determine the range of indices you 219 * can supply. 220 * 221 * @see #getBroadcastItem 222 * @see #finishBroadcast 223 */ 224 public int beginBroadcast() { 225 synchronized (mCallbacks) { 226 final int N = mCallbacks.size(); 227 if (N <= 0) { 228 return 0; 229 } 230 Object[] active = mActiveBroadcast; 231 if (active == null || active.length < N) { 232 mActiveBroadcast = active = new Object[N]; 233 } 234 int i=0; 235 for (Callback cb : mCallbacks.values()) { 236 active[i++] = cb; 237 } 238 return i; 239 } 240 } 241 242 /** 243 * Retrieve an item in the active broadcast that was previously started 244 * with {@link #beginBroadcast}. This can <em>only</em> be called after 245 * the broadcast is started, and its data is no longer valid after 246 * calling {@link #finishBroadcast}. 247 * 248 * <p>Note that it is possible for the process of one of the returned 249 * callbacks to go away before you call it, so you will need to catch 250 * {@link RemoteException} when calling on to the returned object. 251 * The callback list itself, however, will take care of unregistering 252 * these objects once it detects that it is no longer valid, so you can 253 * handle such an exception by simply ignoring it. 254 * 255 * @param index Which of the registered callbacks you would like to 256 * retrieve. Ranges from 0 to 1-{@link #beginBroadcast}. 257 * 258 * @return Returns the callback interface that you can call. This will 259 * always be non-null. 260 * 261 * @see #beginBroadcast 262 */ 263 public E getBroadcastItem(int index) { 264 return ((Callback)mActiveBroadcast[index]).mCallback; 265 } 266 267 /** 268 * Retrieve the cookie associated with the item 269 * returned by {@link #getBroadcastItem(int)}. 270 * 271 * @see #getBroadcastItem 272 */ 273 public Object getBroadcastCookie(int index) { 274 return ((Callback)mActiveBroadcast[index]).mCookie; 275 } 276 277 /** 278 * Clean up the state of a broadcast previously initiated by calling 279 * {@link #beginBroadcast}. This must always be called when you are done 280 * with a broadcast. 281 * 282 * @see #beginBroadcast 283 */ 284 public void finishBroadcast() { 285 Object[] active = mActiveBroadcast; 286 if (active != null) { 287 final int N = active.length; 288 for (int i=0; i<N; i++) { 289 active[i] = null; 290 } 291 } 292 } 293} 294