Search in sources :

Example 11 with ContentObserver

use of android.database.ContentObserver in project storio by pushtorefresh.

the class RxChangesObserverTest method contentObserverShouldReturnFalseOnDeliverSelfNotificationsOnAllSdkVersions.

@Test
public void contentObserverShouldReturnFalseOnDeliverSelfNotificationsOnAllSdkVersions() {
    for (int sdkVersion = MIN_SDK_VERSION; sdkVersion < MAX_SDK_VERSION; sdkVersion++) {
        ContentResolver contentResolver = mock(ContentResolver.class);
        Uri uri = mock(Uri.class);
        final AtomicReference<ContentObserver> contentObserver = new AtomicReference<ContentObserver>();
        doAnswer(new Answer() {

            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                contentObserver.set((ContentObserver) invocation.getArguments()[2]);
                return null;
            }
        }).when(contentResolver).registerContentObserver(same(uri), eq(true), any(ContentObserver.class));
        Handler handler = mock(Handler.class);
        Observable<Changes> observable = RxChangesObserver.observeChanges(contentResolver, singleton(uri), handler, sdkVersion);
        Subscription subscription = observable.subscribe();
        assertThat(contentObserver.get().deliverSelfNotifications()).isFalse();
        subscription.unsubscribe();
    }
}
Also used : Changes(com.pushtorefresh.storio.contentresolver.Changes) Handler(android.os.Handler) AtomicReference(java.util.concurrent.atomic.AtomicReference) Uri(android.net.Uri) ContentResolver(android.content.ContentResolver) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Subscription(rx.Subscription) ContentObserver(android.database.ContentObserver) Test(org.junit.Test)

Example 12 with ContentObserver

use of android.database.ContentObserver in project platform_frameworks_base by android.

the class SettingsProviderTest method setSettingAndAssertSuccessfulChange.

private void setSettingAndAssertSuccessfulChange(Runnable setCommand, final int type, final String name, final String value, final int userId) throws Exception {
    ContentResolver contentResolver = getContext().getContentResolver();
    final Uri settingUri = getBaseUriForType(type);
    final AtomicBoolean success = new AtomicBoolean();
    ContentObserver contentObserver = new ContentObserver(new Handler(Looper.getMainLooper())) {

        public void onChange(boolean selfChange, Uri changeUri, int changeId) {
            Log.i(LOG_TAG, "onChange(" + selfChange + ", " + changeUri + ", " + changeId + ")");
            assertEquals("Wrong change Uri", changeUri, settingUri);
            assertEquals("Wrong user id", userId, changeId);
            String changeValue = getStringViaFrontEndApiSetting(type, name, userId);
            assertEquals("Wrong setting value", value, changeValue);
            success.set(true);
            synchronized (mLock) {
                mLock.notifyAll();
            }
        }
    };
    contentResolver.registerContentObserver(settingUri, false, contentObserver, userId);
    try {
        setCommand.run();
        final long startTimeMillis = SystemClock.uptimeMillis();
        synchronized (mLock) {
            if (success.get()) {
                return;
            }
            final long elapsedTimeMillis = SystemClock.uptimeMillis() - startTimeMillis;
            if (elapsedTimeMillis > WAIT_FOR_SETTING_URI_CHANGE_TIMEOUT_MILLIS) {
                fail("Could not change setting for " + WAIT_FOR_SETTING_URI_CHANGE_TIMEOUT_MILLIS + " ms");
            }
            final long remainingTimeMillis = WAIT_FOR_SETTING_URI_CHANGE_TIMEOUT_MILLIS - elapsedTimeMillis;
            try {
                mLock.wait(remainingTimeMillis);
            } catch (InterruptedException ie) {
            /* ignore */
            }
        }
    } finally {
        contentResolver.unregisterContentObserver(contentObserver);
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Handler(android.os.Handler) Uri(android.net.Uri) ContentResolver(android.content.ContentResolver) ContentObserver(android.database.ContentObserver)

Example 13 with ContentObserver

use of android.database.ContentObserver in project platform_frameworks_base by android.

the class ValidateNotificationPeople method initialize.

public void initialize(Context context, NotificationUsageStats usageStats) {
    if (DEBUG)
        Slog.d(TAG, "Initializing  " + getClass().getSimpleName() + ".");
    mUserToContextMap = new ArrayMap<>();
    mBaseContext = context;
    mUsageStats = usageStats;
    mPeopleCache = new LruCache<String, LookupResult>(PEOPLE_CACHE_SIZE);
    mEnabled = ENABLE_PEOPLE_VALIDATOR && 1 == Settings.Global.getInt(mBaseContext.getContentResolver(), SETTING_ENABLE_PEOPLE_VALIDATOR, 1);
    if (mEnabled) {
        mHandler = new Handler();
        mObserver = new ContentObserver(mHandler) {

            @Override
            public void onChange(boolean selfChange, Uri uri, int userId) {
                super.onChange(selfChange, uri, userId);
                if (DEBUG || mEvictionCount % 100 == 0) {
                    if (VERBOSE)
                        Slog.i(TAG, "mEvictionCount: " + mEvictionCount);
                }
                mPeopleCache.evictAll();
                mEvictionCount++;
            }
        };
        mBaseContext.getContentResolver().registerContentObserver(Contacts.CONTENT_URI, true, mObserver, UserHandle.USER_ALL);
    }
}
Also used : Handler(android.os.Handler) Uri(android.net.Uri) ContentObserver(android.database.ContentObserver)

Example 14 with ContentObserver

use of android.database.ContentObserver in project platform_frameworks_base by android.

the class TelecomLoaderService method registerDefaultAppNotifier.

private void registerDefaultAppNotifier() {
    final PackageManagerInternal packageManagerInternal = LocalServices.getService(PackageManagerInternal.class);
    // Notify the package manager on default app changes
    final Uri defaultSmsAppUri = Settings.Secure.getUriFor(Settings.Secure.SMS_DEFAULT_APPLICATION);
    final Uri defaultDialerAppUri = Settings.Secure.getUriFor(Settings.Secure.DIALER_DEFAULT_APPLICATION);
    ContentObserver contentObserver = new ContentObserver(new Handler(Looper.getMainLooper())) {

        @Override
        public void onChange(boolean selfChange, Uri uri, int userId) {
            if (defaultSmsAppUri.equals(uri)) {
                ComponentName smsComponent = SmsApplication.getDefaultSmsApplication(mContext, true);
                if (smsComponent != null) {
                    packageManagerInternal.grantDefaultPermissionsToDefaultSmsApp(smsComponent.getPackageName(), userId);
                }
            } else if (defaultDialerAppUri.equals(uri)) {
                String packageName = DefaultDialerManager.getDefaultDialerApplication(mContext);
                if (packageName != null) {
                    packageManagerInternal.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
                }
                updateSimCallManagerPermissions(packageManagerInternal, userId);
            }
        }
    };
    mContext.getContentResolver().registerContentObserver(defaultSmsAppUri, false, contentObserver, UserHandle.USER_ALL);
    mContext.getContentResolver().registerContentObserver(defaultDialerAppUri, false, contentObserver, UserHandle.USER_ALL);
}
Also used : PackageManagerInternal(android.content.pm.PackageManagerInternal) Handler(android.os.Handler) ComponentName(android.content.ComponentName) Uri(android.net.Uri) ContentObserver(android.database.ContentObserver)

Example 15 with ContentObserver

use of android.database.ContentObserver in project sqlbrite by square.

the class BriteContentResolver method createQuery.

/**
   * Create an observable which will notify subscribers with a {@linkplain Query query} for
   * execution. Subscribers are responsible for <b>always</b> closing {@link Cursor} instance
   * returned from the {@link Query}.
   * <p>
   * Subscribers will receive an immediate notification for initial data as well as subsequent
   * notifications for when the supplied {@code uri}'s data changes. Unsubscribe when you no longer
   * want updates to a query.
   * <p>
   * Since content resolver triggers are inherently asynchronous, items emitted from the returned
   * observable use the {@link Scheduler} supplied to {@link SqlBrite#wrapContentProvider}. For
   * consistency, the immediate notification sent on subscribe also uses this scheduler. As such,
   * calling {@link Observable#subscribeOn subscribeOn} on the returned observable has no effect.
   * <p>
   * Note: To skip the immediate notification and only receive subsequent notifications when data
   * has changed call {@code skip(1)} on the returned observable.
   * <p>
   * <b>Warning:</b> this method does not perform the query! Only by subscribing to the returned
   * {@link Observable} will the operation occur.
   *
   * @see ContentResolver#query(Uri, String[], String, String[], String)
   * @see ContentResolver#registerContentObserver(Uri, boolean, ContentObserver)
   */
@CheckResult
@NonNull
public QueryObservable createQuery(@NonNull final Uri uri, @Nullable final String[] projection, @Nullable final String selection, @Nullable final String[] selectionArgs, @Nullable final String sortOrder, final boolean notifyForDescendents) {
    final Query query = new Query() {

        @Override
        public Cursor run() {
            long startNanos = nanoTime();
            Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder);
            if (logging) {
                long tookMillis = NANOSECONDS.toMillis(nanoTime() - startNanos);
                log("QUERY (%sms)\n  uri: %s\n  projection: %s\n  selection: %s\n  selectionArgs: %s\n  " + "sortOrder: %s\n  notifyForDescendents: %s", tookMillis, uri, Arrays.toString(projection), selection, Arrays.toString(selectionArgs), sortOrder, notifyForDescendents);
            }
            return cursor;
        }
    };
    OnSubscribe<Query> subscribe = new OnSubscribe<Query>() {

        @Override
        public void call(final Subscriber<? super Query> subscriber) {
            final ContentObserver observer = new ContentObserver(contentObserverHandler) {

                @Override
                public void onChange(boolean selfChange) {
                    subscriber.onNext(query);
                }
            };
            contentResolver.registerContentObserver(uri, notifyForDescendents, observer);
            subscriber.add(Subscriptions.create(new Action0() {

                @Override
                public void call() {
                    contentResolver.unregisterContentObserver(observer);
                }
            }));
            // Trigger initial query.
            subscriber.onNext(query);
        }
    };
    final Observable<Query> queryObservable = //
    Observable.create(subscribe).onBackpressureLatest().observeOn(//
    scheduler).compose(// Apply the user's query transformer.
    queryTransformer).onBackpressureLatest();
    // TODO switch to .to() when non-@Experimental
    return new QueryObservable(new OnSubscribe<Query>() {

        @Override
        public void call(Subscriber<? super Query> subscriber) {
            queryObservable.unsafeSubscribe(subscriber);
        }
    });
}
Also used : Action0(rx.functions.Action0) Query(com.squareup.sqlbrite.SqlBrite.Query) Subscriber(rx.Subscriber) OnSubscribe(rx.Observable.OnSubscribe) Cursor(android.database.Cursor) ContentObserver(android.database.ContentObserver) CheckResult(android.support.annotation.CheckResult) NonNull(android.support.annotation.NonNull)

Aggregations

ContentObserver (android.database.ContentObserver)96 Handler (android.os.Handler)41 Uri (android.net.Uri)35 ContentResolver (android.content.ContentResolver)28 Intent (android.content.Intent)16 IntentFilter (android.content.IntentFilter)16 BroadcastReceiver (android.content.BroadcastReceiver)9 Context (android.content.Context)9 PendingIntent (android.app.PendingIntent)7 RemoteException (android.os.RemoteException)7 Test (org.junit.Test)7 AppOpsManager (android.app.AppOpsManager)6 GeofenceManager (com.android.server.location.GeofenceManager)6 LocationBlacklist (com.android.server.location.LocationBlacklist)6 LocationFudger (com.android.server.location.LocationFudger)6 HashSet (java.util.HashSet)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6 Mockito.doAnswer (org.mockito.Mockito.doAnswer)6 InvocationOnMock (org.mockito.invocation.InvocationOnMock)6 Answer (org.mockito.stubbing.Answer)6