2 * Copyright (C) 2006 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.server.content;
19 import android.Manifest;
20 import android.accounts.Account;
21 import android.app.ActivityManager;
22 import android.content.ContentResolver;
23 import android.content.Context;
24 import android.content.IContentService;
25 import android.content.ISyncStatusObserver;
26 import android.content.PeriodicSync;
27 import android.content.SyncAdapterType;
28 import android.content.SyncInfo;
29 import android.content.SyncRequest;
30 import android.content.SyncStatusInfo;
31 import android.database.IContentObserver;
32 import android.database.sqlite.SQLiteException;
33 import android.net.Uri;
34 import android.os.Binder;
35 import android.os.Bundle;
36 import android.os.IBinder;
37 import android.os.Parcel;
38 import android.os.RemoteException;
39 import android.os.ServiceManager;
40 import android.os.SystemProperties;
41 import android.os.UserHandle;
42 import android.text.TextUtils;
43 import android.util.Log;
44 import android.util.Pair;
45 import android.util.Slog;
46 import android.util.SparseIntArray;
48 import java.io.FileDescriptor;
49 import java.io.PrintWriter;
50 import java.security.InvalidParameterException;
51 import java.util.ArrayList;
52 import java.util.Collections;
53 import java.util.Comparator;
54 import java.util.List;
59 public final class ContentService extends IContentService.Stub {
60 private static final String TAG = "ContentService";
61 private Context mContext;
62 private boolean mFactoryTest;
63 private final ObserverNode mRootNode = new ObserverNode("");
64 private SyncManager mSyncManager = null;
65 private final Object mSyncManagerLock = new Object();
67 private SyncManager getSyncManager() {
68 if (SystemProperties.getBoolean("config.disable_network", false)) {
72 synchronized(mSyncManagerLock) {
74 // Try to create the SyncManager, return null if it fails (e.g. the disk is full).
75 if (mSyncManager == null) mSyncManager = new SyncManager(mContext, mFactoryTest);
76 } catch (SQLiteException e) {
77 Log.e(TAG, "Can't create SyncManager", e);
84 protected synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
85 mContext.enforceCallingOrSelfPermission(Manifest.permission.DUMP,
86 "caller doesn't have the DUMP permission");
88 // This makes it so that future permission checks will be in the context of this
89 // process rather than the caller's process. We will restore this before returning.
90 long identityToken = clearCallingIdentity();
92 if (mSyncManager == null) {
93 pw.println("No SyncManager created! (Disk full?)");
95 mSyncManager.dump(fd, pw);
98 pw.println("Observer tree:");
99 synchronized (mRootNode) {
100 int[] counts = new int[2];
101 final SparseIntArray pidCounts = new SparseIntArray();
102 mRootNode.dumpLocked(fd, pw, args, "", " ", counts, pidCounts);
104 ArrayList<Integer> sorted = new ArrayList<Integer>();
105 for (int i=0; i<pidCounts.size(); i++) {
106 sorted.add(pidCounts.keyAt(i));
108 Collections.sort(sorted, new Comparator<Integer>() {
110 public int compare(Integer lhs, Integer rhs) {
111 int lc = pidCounts.get(lhs);
112 int rc = pidCounts.get(rhs);
115 } else if (lc > rc) {
122 for (int i=0; i<sorted.size(); i++) {
123 int pid = sorted.get(i);
124 pw.print(" pid "); pw.print(pid); pw.print(": ");
125 pw.print(pidCounts.get(pid)); pw.println(" observers");
128 pw.print(" Total number of nodes: "); pw.println(counts[0]);
129 pw.print(" Total number of observers: "); pw.println(counts[1]);
132 restoreCallingIdentity(identityToken);
137 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
138 throws RemoteException {
140 return super.onTransact(code, data, reply, flags);
141 } catch (RuntimeException e) {
142 // The content service only throws security exceptions, so let's
144 if (!(e instanceof SecurityException)) {
145 Slog.wtf(TAG, "Content Service Crash", e);
151 /*package*/ ContentService(Context context, boolean factoryTest) {
153 mFactoryTest = factoryTest;
156 public void systemReady() {
161 * Register a content observer tied to a specific user's view of the provider.
162 * @param userHandle the user whose view of the provider is to be observed. May be
163 * the calling user without requiring any permission, otherwise the caller needs to
164 * hold the INTERACT_ACROSS_USERS_FULL permission. Pseudousers USER_ALL and
165 * USER_CURRENT are properly handled; all other pseudousers are forbidden.
168 public void registerContentObserver(Uri uri, boolean notifyForDescendants,
169 IContentObserver observer, int userHandle) {
170 if (observer == null || uri == null) {
171 throw new IllegalArgumentException("You must pass a valid uri and observer");
174 final int callingUser = UserHandle.getCallingUserId();
175 if (callingUser != userHandle) {
176 mContext.enforceCallingOrSelfPermission(Manifest.permission.INTERACT_ACROSS_USERS_FULL,
177 "no permission to observe other users' provider view");
180 if (userHandle < 0) {
181 if (userHandle == UserHandle.USER_CURRENT) {
182 userHandle = ActivityManager.getCurrentUser();
183 } else if (userHandle != UserHandle.USER_ALL) {
184 throw new InvalidParameterException("Bad user handle for registerContentObserver: "
189 synchronized (mRootNode) {
190 mRootNode.addObserverLocked(uri, observer, notifyForDescendants, mRootNode,
191 Binder.getCallingUid(), Binder.getCallingPid(), userHandle);
192 if (false) Log.v(TAG, "Registered observer " + observer + " at " + uri +
193 " with notifyForDescendants " + notifyForDescendants);
197 public void registerContentObserver(Uri uri, boolean notifyForDescendants,
198 IContentObserver observer) {
199 registerContentObserver(uri, notifyForDescendants, observer,
200 UserHandle.getCallingUserId());
203 public void unregisterContentObserver(IContentObserver observer) {
204 if (observer == null) {
205 throw new IllegalArgumentException("You must pass a valid observer");
207 synchronized (mRootNode) {
208 mRootNode.removeObserverLocked(observer);
209 if (false) Log.v(TAG, "Unregistered observer " + observer);
214 * Notify observers of a particular user's view of the provider.
215 * @param userHandle the user whose view of the provider is to be notified. May be
216 * the calling user without requiring any permission, otherwise the caller needs to
217 * hold the INTERACT_ACROSS_USERS_FULL permission. Pseudousers USER_ALL and
218 * USER_CURRENT are properly interpreted; no other pseudousers are allowed.
221 public void notifyChange(Uri uri, IContentObserver observer,
222 boolean observerWantsSelfNotifications, boolean syncToNetwork,
224 if (Log.isLoggable(TAG, Log.VERBOSE)) {
225 Log.v(TAG, "Notifying update of " + uri + " for user " + userHandle
226 + " from observer " + observer + ", syncToNetwork " + syncToNetwork);
229 // Notify for any user other than the caller's own requires permission.
230 final int callingUserHandle = UserHandle.getCallingUserId();
231 if (userHandle != callingUserHandle) {
232 mContext.enforceCallingOrSelfPermission(Manifest.permission.INTERACT_ACROSS_USERS_FULL,
233 "no permission to notify other users");
236 // We passed the permission check; resolve pseudouser targets as appropriate
237 if (userHandle < 0) {
238 if (userHandle == UserHandle.USER_CURRENT) {
239 userHandle = ActivityManager.getCurrentUser();
240 } else if (userHandle != UserHandle.USER_ALL) {
241 throw new InvalidParameterException("Bad user handle for notifyChange: "
246 final int uid = Binder.getCallingUid();
247 // This makes it so that future permission checks will be in the context of this
248 // process rather than the caller's process. We will restore this before returning.
249 long identityToken = clearCallingIdentity();
251 ArrayList<ObserverCall> calls = new ArrayList<ObserverCall>();
252 synchronized (mRootNode) {
253 mRootNode.collectObserversLocked(uri, 0, observer, observerWantsSelfNotifications,
256 final int numCalls = calls.size();
257 for (int i=0; i<numCalls; i++) {
258 ObserverCall oc = calls.get(i);
260 oc.mObserver.onChange(oc.mSelfChange, uri);
261 if (Log.isLoggable(TAG, Log.VERBOSE)) {
262 Log.v(TAG, "Notified " + oc.mObserver + " of " + "update at " + uri);
264 } catch (RemoteException ex) {
265 synchronized (mRootNode) {
266 Log.w(TAG, "Found dead observer, removing");
267 IBinder binder = oc.mObserver.asBinder();
268 final ArrayList<ObserverNode.ObserverEntry> list
269 = oc.mNode.mObservers;
270 int numList = list.size();
271 for (int j=0; j<numList; j++) {
272 ObserverNode.ObserverEntry oe = list.get(j);
273 if (oe.observer.asBinder() == binder) {
283 SyncManager syncManager = getSyncManager();
284 if (syncManager != null) {
285 syncManager.scheduleLocalSync(null /* all accounts */, callingUserHandle, uid,
290 restoreCallingIdentity(identityToken);
294 public void notifyChange(Uri uri, IContentObserver observer,
295 boolean observerWantsSelfNotifications, boolean syncToNetwork) {
296 notifyChange(uri, observer, observerWantsSelfNotifications, syncToNetwork,
297 UserHandle.getCallingUserId());
301 * Hide this class since it is not part of api,
302 * but current unittest framework requires it to be public
306 public static final class ObserverCall {
307 final ObserverNode mNode;
308 final IContentObserver mObserver;
309 final boolean mSelfChange;
311 ObserverCall(ObserverNode node, IContentObserver observer, boolean selfChange) {
313 mObserver = observer;
314 mSelfChange = selfChange;
319 public void requestSync(Account account, String authority, Bundle extras) {
320 ContentResolver.validateSyncExtrasBundle(extras);
321 int userId = UserHandle.getCallingUserId();
322 int uId = Binder.getCallingUid();
324 // This makes it so that future permission checks will be in the context of this
325 // process rather than the caller's process. We will restore this before returning.
326 long identityToken = clearCallingIdentity();
328 SyncManager syncManager = getSyncManager();
329 if (syncManager != null) {
330 syncManager.scheduleSync(account, userId, uId, authority, extras,
331 0 /* no delay */, 0 /* no delay */,
332 false /* onlyThoseWithUnkownSyncableState */);
335 restoreCallingIdentity(identityToken);
340 * Request a sync with a generic {@link android.content.SyncRequest} object. This will be
342 * periodic OR one-off sync.
344 * anonymous OR provider sync.
345 * Depending on the request, we enqueue to suit in the SyncManager.
346 * @param request The request object. Validation of this object is done by its builder.
349 public void sync(SyncRequest request) {
350 Bundle extras = request.getBundle();
351 long flextime = request.getSyncFlexTime();
352 long runAtTime = request.getSyncRunTime();
353 int userId = UserHandle.getCallingUserId();
354 int uId = Binder.getCallingUid();
356 // This makes it so that future permission checks will be in the context of this
357 // process rather than the caller's process. We will restore this before returning.
358 long identityToken = clearCallingIdentity();
360 SyncManager syncManager = getSyncManager();
361 if (syncManager != null) {
362 if (request.hasAuthority()) {
363 // Sync Adapter registered with the system - old API.
364 final Account account = request.getAccount();
365 final String provider = request.getProvider();
366 if (request.isPeriodic()) {
367 mContext.enforceCallingOrSelfPermission(
368 Manifest.permission.WRITE_SYNC_SETTINGS,
369 "no permission to write the sync settings");
370 if (runAtTime < 60) {
371 Slog.w(TAG, "Requested poll frequency of " + runAtTime
372 + " seconds being rounded up to 60 seconds.");
375 PeriodicSync syncToAdd =
376 new PeriodicSync(account, provider, extras, runAtTime, flextime);
377 getSyncManager().getSyncStorageEngine().addPeriodicSync(syncToAdd, userId);
379 long beforeRuntimeMillis = (flextime) * 1000;
380 long runtimeMillis = runAtTime * 1000;
381 syncManager.scheduleSync(
382 account, userId, uId, provider, extras,
383 beforeRuntimeMillis, runtimeMillis,
384 false /* onlyThoseWithUnknownSyncableState */);
387 Log.w(TAG, "Unrecognised sync parameters, doing nothing.");
391 restoreCallingIdentity(identityToken);
396 * Clear all scheduled sync operations that match the uri and cancel the active sync
397 * if they match the authority and account, if they are present.
398 * @param account filter the pending and active syncs to cancel using this account
399 * @param authority filter the pending and active syncs to cancel using this authority
402 public void cancelSync(Account account, String authority) {
403 if (authority != null && authority.length() == 0) {
404 throw new IllegalArgumentException("Authority must be non-empty");
407 int userId = UserHandle.getCallingUserId();
408 // This makes it so that future permission checks will be in the context of this
409 // process rather than the caller's process. We will restore this before returning.
410 long identityToken = clearCallingIdentity();
412 SyncManager syncManager = getSyncManager();
413 if (syncManager != null) {
414 syncManager.clearScheduledSyncOperations(account, userId, authority);
415 syncManager.cancelActiveSync(account, userId, authority);
418 restoreCallingIdentity(identityToken);
423 * Get information about the SyncAdapters that are known to the system.
424 * @return an array of SyncAdapters that have registered with the system
427 public SyncAdapterType[] getSyncAdapterTypes() {
428 // This makes it so that future permission checks will be in the context of this
429 // process rather than the caller's process. We will restore this before returning.
430 final int userId = UserHandle.getCallingUserId();
431 final long identityToken = clearCallingIdentity();
433 SyncManager syncManager = getSyncManager();
434 return syncManager.getSyncAdapterTypes(userId);
436 restoreCallingIdentity(identityToken);
441 public boolean getSyncAutomatically(Account account, String providerName) {
442 mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_SETTINGS,
443 "no permission to read the sync settings");
445 int userId = UserHandle.getCallingUserId();
446 long identityToken = clearCallingIdentity();
448 SyncManager syncManager = getSyncManager();
449 if (syncManager != null) {
450 return syncManager.getSyncStorageEngine().getSyncAutomatically(
451 account, userId, providerName);
454 restoreCallingIdentity(identityToken);
460 public void setSyncAutomatically(Account account, String providerName, boolean sync) {
461 if (TextUtils.isEmpty(providerName)) {
462 throw new IllegalArgumentException("Authority must be non-empty");
464 mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
465 "no permission to write the sync settings");
467 int userId = UserHandle.getCallingUserId();
468 long identityToken = clearCallingIdentity();
470 SyncManager syncManager = getSyncManager();
471 if (syncManager != null) {
472 syncManager.getSyncStorageEngine().setSyncAutomatically(
473 account, userId, providerName, sync);
476 restoreCallingIdentity(identityToken);
480 /** Old API. Schedule periodic sync with default flex time. */
482 public void addPeriodicSync(Account account, String authority, Bundle extras,
483 long pollFrequency) {
484 if (account == null) {
485 throw new IllegalArgumentException("Account must not be null");
487 if (TextUtils.isEmpty(authority)) {
488 throw new IllegalArgumentException("Authority must not be empty.");
490 mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
491 "no permission to write the sync settings");
493 int userId = UserHandle.getCallingUserId();
494 if (pollFrequency < 60) {
495 Slog.w(TAG, "Requested poll frequency of " + pollFrequency
496 + " seconds being rounded up to 60 seconds.");
500 long identityToken = clearCallingIdentity();
502 // Add default flex time to this sync.
503 PeriodicSync syncToAdd =
504 new PeriodicSync(account, authority, extras,
506 SyncStorageEngine.calculateDefaultFlexTime(pollFrequency));
507 getSyncManager().getSyncStorageEngine().addPeriodicSync(syncToAdd, userId);
509 restoreCallingIdentity(identityToken);
514 public void removePeriodicSync(Account account, String authority, Bundle extras) {
515 if (account == null) {
516 throw new IllegalArgumentException("Account must not be null");
518 if (TextUtils.isEmpty(authority)) {
519 throw new IllegalArgumentException("Authority must not be empty");
521 mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
522 "no permission to write the sync settings");
524 int userId = UserHandle.getCallingUserId();
525 long identityToken = clearCallingIdentity();
527 PeriodicSync syncToRemove = new PeriodicSync(account, authority, extras,
528 0 /* Not read for removal */, 0 /* Not read for removal */);
529 getSyncManager().getSyncStorageEngine().removePeriodicSync(syncToRemove, userId);
531 restoreCallingIdentity(identityToken);
537 * @param request Sync to remove.
539 public void removeSync(SyncRequest request) {
544 public List<PeriodicSync> getPeriodicSyncs(Account account, String providerName) {
545 if (account == null) {
546 throw new IllegalArgumentException("Account must not be null");
548 if (TextUtils.isEmpty(providerName)) {
549 throw new IllegalArgumentException("Authority must not be empty");
551 mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_SETTINGS,
552 "no permission to read the sync settings");
554 int userId = UserHandle.getCallingUserId();
555 long identityToken = clearCallingIdentity();
557 return getSyncManager().getSyncStorageEngine().getPeriodicSyncs(
558 account, userId, providerName);
560 restoreCallingIdentity(identityToken);
564 public int getIsSyncable(Account account, String providerName) {
565 mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_SETTINGS,
566 "no permission to read the sync settings");
567 int userId = UserHandle.getCallingUserId();
569 long identityToken = clearCallingIdentity();
571 SyncManager syncManager = getSyncManager();
572 if (syncManager != null) {
573 return syncManager.getIsSyncable(
574 account, userId, providerName);
577 restoreCallingIdentity(identityToken);
583 public void setIsSyncable(Account account, String providerName, int syncable) {
584 if (TextUtils.isEmpty(providerName)) {
585 throw new IllegalArgumentException("Authority must not be empty");
587 mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
588 "no permission to write the sync settings");
590 int userId = UserHandle.getCallingUserId();
591 long identityToken = clearCallingIdentity();
593 SyncManager syncManager = getSyncManager();
594 if (syncManager != null) {
595 syncManager.getSyncStorageEngine().setIsSyncable(
596 account, userId, providerName, syncable);
599 restoreCallingIdentity(identityToken);
604 public boolean getMasterSyncAutomatically() {
605 mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_SETTINGS,
606 "no permission to read the sync settings");
608 int userId = UserHandle.getCallingUserId();
609 long identityToken = clearCallingIdentity();
611 SyncManager syncManager = getSyncManager();
612 if (syncManager != null) {
613 return syncManager.getSyncStorageEngine().getMasterSyncAutomatically(userId);
616 restoreCallingIdentity(identityToken);
622 public void setMasterSyncAutomatically(boolean flag) {
623 mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
624 "no permission to write the sync settings");
626 int userId = UserHandle.getCallingUserId();
627 long identityToken = clearCallingIdentity();
629 SyncManager syncManager = getSyncManager();
630 if (syncManager != null) {
631 syncManager.getSyncStorageEngine().setMasterSyncAutomatically(flag, userId);
634 restoreCallingIdentity(identityToken);
638 public boolean isSyncActive(Account account, String authority) {
639 mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_STATS,
640 "no permission to read the sync stats");
641 int userId = UserHandle.getCallingUserId();
643 long identityToken = clearCallingIdentity();
645 SyncManager syncManager = getSyncManager();
646 if (syncManager != null) {
647 return syncManager.getSyncStorageEngine().isSyncActive(
648 account, userId, authority);
651 restoreCallingIdentity(identityToken);
656 public List<SyncInfo> getCurrentSyncs() {
657 mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_STATS,
658 "no permission to read the sync stats");
660 int userId = UserHandle.getCallingUserId();
661 long identityToken = clearCallingIdentity();
663 return getSyncManager().getSyncStorageEngine().getCurrentSyncsCopy(userId);
665 restoreCallingIdentity(identityToken);
669 public SyncStatusInfo getSyncStatus(Account account, String authority) {
670 if (TextUtils.isEmpty(authority)) {
671 throw new IllegalArgumentException("Authority must not be empty");
673 mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_STATS,
674 "no permission to read the sync stats");
676 int userId = UserHandle.getCallingUserId();
677 long identityToken = clearCallingIdentity();
679 SyncManager syncManager = getSyncManager();
680 if (syncManager != null) {
681 return syncManager.getSyncStorageEngine().getStatusByAccountAndAuthority(
682 account, userId, authority);
685 restoreCallingIdentity(identityToken);
690 public boolean isSyncPending(Account account, String authority) {
691 mContext.enforceCallingOrSelfPermission(Manifest.permission.READ_SYNC_STATS,
692 "no permission to read the sync stats");
694 int userId = UserHandle.getCallingUserId();
695 long identityToken = clearCallingIdentity();
697 SyncManager syncManager = getSyncManager();
698 if (syncManager != null) {
699 return syncManager.getSyncStorageEngine().isSyncPending(account, userId, authority);
702 restoreCallingIdentity(identityToken);
707 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
708 long identityToken = clearCallingIdentity();
710 SyncManager syncManager = getSyncManager();
711 if (syncManager != null && callback != null) {
712 syncManager.getSyncStorageEngine().addStatusChangeListener(mask, callback);
715 restoreCallingIdentity(identityToken);
719 public void removeStatusChangeListener(ISyncStatusObserver callback) {
720 long identityToken = clearCallingIdentity();
722 SyncManager syncManager = getSyncManager();
723 if (syncManager != null && callback != null) {
724 syncManager.getSyncStorageEngine().removeStatusChangeListener(callback);
727 restoreCallingIdentity(identityToken);
731 public static ContentService main(Context context, boolean factoryTest) {
732 ContentService service = new ContentService(context, factoryTest);
733 ServiceManager.addService(ContentResolver.CONTENT_SERVICE_NAME, service);
738 * Hide this class since it is not part of api,
739 * but current unittest framework requires it to be public
742 public static final class ObserverNode {
743 private class ObserverEntry implements IBinder.DeathRecipient {
744 public final IContentObserver observer;
745 public final int uid;
746 public final int pid;
747 public final boolean notifyForDescendants;
748 private final int userHandle;
749 private final Object observersLock;
751 public ObserverEntry(IContentObserver o, boolean n, Object observersLock,
752 int _uid, int _pid, int _userHandle) {
753 this.observersLock = observersLock;
757 userHandle = _userHandle;
758 notifyForDescendants = n;
760 observer.asBinder().linkToDeath(this, 0);
761 } catch (RemoteException e) {
766 public void binderDied() {
767 synchronized (observersLock) {
768 removeObserverLocked(observer);
772 public void dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
773 String name, String prefix, SparseIntArray pidCounts) {
774 pidCounts.put(pid, pidCounts.get(pid)+1);
775 pw.print(prefix); pw.print(name); pw.print(": pid=");
776 pw.print(pid); pw.print(" uid=");
777 pw.print(uid); pw.print(" user=");
778 pw.print(userHandle); pw.print(" target=");
779 pw.println(Integer.toHexString(System.identityHashCode(
780 observer != null ? observer.asBinder() : null)));
784 public static final int INSERT_TYPE = 0;
785 public static final int UPDATE_TYPE = 1;
786 public static final int DELETE_TYPE = 2;
788 private String mName;
789 private ArrayList<ObserverNode> mChildren = new ArrayList<ObserverNode>();
790 private ArrayList<ObserverEntry> mObservers = new ArrayList<ObserverEntry>();
792 public ObserverNode(String name) {
796 public void dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
797 String name, String prefix, int[] counts, SparseIntArray pidCounts) {
798 String innerName = null;
799 if (mObservers.size() > 0) {
800 if ("".equals(name)) {
803 innerName = name + "/" + mName;
805 for (int i=0; i<mObservers.size(); i++) {
807 mObservers.get(i).dumpLocked(fd, pw, args, innerName, prefix,
811 if (mChildren.size() > 0) {
812 if (innerName == null) {
813 if ("".equals(name)) {
816 innerName = name + "/" + mName;
819 for (int i=0; i<mChildren.size(); i++) {
821 mChildren.get(i).dumpLocked(fd, pw, args, innerName, prefix,
827 private String getUriSegment(Uri uri, int index) {
830 return uri.getAuthority();
832 return uri.getPathSegments().get(index - 1);
839 private int countUriSegments(Uri uri) {
843 return uri.getPathSegments().size() + 1;
846 // Invariant: userHandle is either a hard user number or is USER_ALL
847 public void addObserverLocked(Uri uri, IContentObserver observer,
848 boolean notifyForDescendants, Object observersLock,
849 int uid, int pid, int userHandle) {
850 addObserverLocked(uri, 0, observer, notifyForDescendants, observersLock,
851 uid, pid, userHandle);
854 private void addObserverLocked(Uri uri, int index, IContentObserver observer,
855 boolean notifyForDescendants, Object observersLock,
856 int uid, int pid, int userHandle) {
857 // If this is the leaf node add the observer
858 if (index == countUriSegments(uri)) {
859 mObservers.add(new ObserverEntry(observer, notifyForDescendants, observersLock,
860 uid, pid, userHandle));
864 // Look to see if the proper child already exists
865 String segment = getUriSegment(uri, index);
866 if (segment == null) {
867 throw new IllegalArgumentException("Invalid Uri (" + uri + ") used for observer");
869 int N = mChildren.size();
870 for (int i = 0; i < N; i++) {
871 ObserverNode node = mChildren.get(i);
872 if (node.mName.equals(segment)) {
873 node.addObserverLocked(uri, index + 1, observer, notifyForDescendants,
874 observersLock, uid, pid, userHandle);
879 // No child found, create one
880 ObserverNode node = new ObserverNode(segment);
882 node.addObserverLocked(uri, index + 1, observer, notifyForDescendants,
883 observersLock, uid, pid, userHandle);
886 public boolean removeObserverLocked(IContentObserver observer) {
887 int size = mChildren.size();
888 for (int i = 0; i < size; i++) {
889 boolean empty = mChildren.get(i).removeObserverLocked(observer);
897 IBinder observerBinder = observer.asBinder();
898 size = mObservers.size();
899 for (int i = 0; i < size; i++) {
900 ObserverEntry entry = mObservers.get(i);
901 if (entry.observer.asBinder() == observerBinder) {
902 mObservers.remove(i);
903 // We no longer need to listen for death notifications. Remove it.
904 observerBinder.unlinkToDeath(entry, 0);
909 if (mChildren.size() == 0 && mObservers.size() == 0) {
915 private void collectMyObserversLocked(boolean leaf, IContentObserver observer,
916 boolean observerWantsSelfNotifications, int targetUserHandle,
917 ArrayList<ObserverCall> calls) {
918 int N = mObservers.size();
919 IBinder observerBinder = observer == null ? null : observer.asBinder();
920 for (int i = 0; i < N; i++) {
921 ObserverEntry entry = mObservers.get(i);
923 // Don't notify the observer if it sent the notification and isn't interested
924 // in self notifications
925 boolean selfChange = (entry.observer.asBinder() == observerBinder);
926 if (selfChange && !observerWantsSelfNotifications) {
930 // Does this observer match the target user?
931 if (targetUserHandle == UserHandle.USER_ALL
932 || entry.userHandle == UserHandle.USER_ALL
933 || targetUserHandle == entry.userHandle) {
934 // Make sure the observer is interested in the notification
935 if (leaf || (!leaf && entry.notifyForDescendants)) {
936 calls.add(new ObserverCall(this, entry.observer, selfChange));
943 * targetUserHandle is either a hard user handle or is USER_ALL
945 public void collectObserversLocked(Uri uri, int index, IContentObserver observer,
946 boolean observerWantsSelfNotifications, int targetUserHandle,
947 ArrayList<ObserverCall> calls) {
948 String segment = null;
949 int segmentCount = countUriSegments(uri);
950 if (index >= segmentCount) {
951 // This is the leaf node, notify all observers
952 collectMyObserversLocked(true, observer, observerWantsSelfNotifications,
953 targetUserHandle, calls);
954 } else if (index < segmentCount){
955 segment = getUriSegment(uri, index);
956 // Notify any observers at this level who are interested in descendants
957 collectMyObserversLocked(false, observer, observerWantsSelfNotifications,
958 targetUserHandle, calls);
961 int N = mChildren.size();
962 for (int i = 0; i < N; i++) {
963 ObserverNode node = mChildren.get(i);
964 if (segment == null || node.mName.equals(segment)) {
965 // We found the child,
966 node.collectObserversLocked(uri, index + 1,
967 observer, observerWantsSelfNotifications, targetUserHandle, calls);
968 if (segment != null) {