android.content.ContentResolver#registerContentObserver ( )源码实例Demo

下面列出了android.content.ContentResolver#registerContentObserver ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hackerskeyboard   文件: UserDictionary.java
public UserDictionary(Context context, String locale) {
    super(context, Suggest.DIC_USER);
    mLocale = locale;
    // Perform a managed query. The Activity will handle closing and requerying the cursor
    // when needed.
    ContentResolver cres = context.getContentResolver();
    
    cres.registerContentObserver(Words.CONTENT_URI, true, mObserver = new ContentObserver(null) {
        @Override
        public void onChange(boolean self) {
            setRequiresReload(true);
        }
    });

    loadDictionary();
}
 
源代码2 项目: android_9.0.0_r45   文件: BatteryService.java
@Override
public void onBootPhase(int phase) {
    if (phase == PHASE_ACTIVITY_MANAGER_READY) {
        // check our power situation now that it is safe to display the shutdown dialog.
        synchronized (mLock) {
            ContentObserver obs = new ContentObserver(mHandler) {
                @Override
                public void onChange(boolean selfChange) {
                    synchronized (mLock) {
                        updateBatteryWarningLevelLocked();
                    }
                }
            };
            final ContentResolver resolver = mContext.getContentResolver();
            resolver.registerContentObserver(Settings.Global.getUriFor(
                    Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL),
                    false, obs, UserHandle.USER_ALL);
            updateBatteryWarningLevelLocked();
        }
    }
}
 
public void registerObserver(final ContactsChangedListener listener) {
    if (!PermissionsUtil.checkAllPermissionsGranted(
            mContext, Manifest.permission.READ_CONTACTS)) {
        Log.i(TAG, "No permission to read contacts. Not registering the observer.");
        // do nothing if we do not have the permission to read contacts.
        return;
    }

    if (DebugFlags.DEBUG_ENABLED) {
        Log.d(TAG, "registerObserver()");
    }
    mContactsChangedListener = listener;
    mContentObserver = new ContentObserver(null /* handler */) {
        @Override
        public void onChange(boolean self) {
            ExecutorUtils.getBackgroundExecutor(ExecutorUtils.KEYBOARD)
                    .execute(ContactsContentObserver.this);
        }
    };
    final ContentResolver contentResolver = mContext.getContentResolver();
    contentResolver.registerContentObserver(Contacts.CONTENT_URI, true, mContentObserver);
}
 
源代码4 项目: android_9.0.0_r45   文件: TextClock.java
private void registerObserver() {
    if (mRegistered) {
        if (mFormatChangeObserver == null) {
            mFormatChangeObserver = new FormatChangeObserver(getHandler());
        }
        final ContentResolver resolver = getContext().getContentResolver();
        Uri uri = Settings.System.getUriFor(Settings.System.TIME_12_24);
        if (mShowCurrentUserTime) {
            resolver.registerContentObserver(uri, true,
                    mFormatChangeObserver, UserHandle.USER_ALL);
        } else {
            resolver.registerContentObserver(uri, true,
                    mFormatChangeObserver);
        }
    }
}
 
源代码5 项目: openboard   文件: ContactsContentObserver.java
public void registerObserver(final ContactsChangedListener listener) {
    if (!PermissionsUtil.checkAllPermissionsGranted(
            mContext, Manifest.permission.READ_CONTACTS)) {
        Log.i(TAG, "No permission to read contacts. Not registering the observer.");
        // do nothing if we do not have the permission to read contacts.
        return;
    }

    if (DebugFlags.DEBUG_ENABLED) {
        Log.d(TAG, "registerObserver()");
    }
    mContactsChangedListener = listener;
    mContentObserver = new ContentObserver(null /* handler */) {
        @Override
        public void onChange(boolean self) {
            ExecutorUtils.getBackgroundExecutor(ExecutorUtils.KEYBOARD)
                    .execute(ContactsContentObserver.this);
        }
    };
    final ContentResolver contentResolver = mContext.getContentResolver();
    contentResolver.registerContentObserver(Contacts.CONTENT_URI, true, mContentObserver);
}
 
源代码6 项目: FilePicker   文件: MediaFileViewModel.java
private MediaFileViewModel(ContentResolver contentResolver, Configurations configs, Long dirId) {
    this.contentResolver = contentResolver;

    MediaFileDataSource.Factory mediaFileDataSourceFactory = new MediaFileDataSource.Factory(contentResolver, configs, dirId);

    mediaFiles = new LivePagedListBuilder<>(
            mediaFileDataSourceFactory,
            new PagedList.Config.Builder()
                    .setPageSize(Configurations.PAGE_SIZE)
                    .setInitialLoadSizeHint(15)
                    .setMaxSize(Configurations.PAGE_SIZE * 3)
                    .setPrefetchDistance(Configurations.PREFETCH_DISTANCE)
                    .setEnablePlaceholders(false)
                    .build()
    ).build();

    contentResolver.registerContentObserver(mediaFileDataSourceFactory.getUri(), true, contentObserver);
}
 
private void registerContentObservers() {
	ContentResolver cr = getContentResolver();
	handler = new Handler();		
	mTaskContentObserver = new TaskContentObserver(handler);
	cr.registerContentObserver(TaskSyncContentProvider.CONTENT_URI, true,
			mTaskContentObserver);
}
 
源代码8 项目: FastAndroid   文件: MediaStoreDataLoader.java
private void registerContentObserver() {
    if (!observerRegistered) {
        ContentResolver cr = getContext().getContentResolver();
        cr.registerContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, false, forceLoadContentObserver);
        cr.registerContentObserver(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, false, forceLoadContentObserver);
        observerRegistered = true;
    }
}
 
AndroidWordLevelSpellCheckerSession(final AndroidSpellCheckerService service) {
    mService = service;
    final ContentResolver cres = service.getContentResolver();

    mObserver = new ContentObserver(null) {
        @Override
        public void onChange(boolean self) {
            mSuggestionsCache.clearCache();
        }
    };
    cres.registerContentObserver(Words.CONTENT_URI, true, mObserver);
}
 
源代码10 项目: LaunchEnr   文件: Launcher.java
static void initContentObserver(Activity activity) {

            Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;

            ContentResolver contentResolver = activity.getContentResolver();

            contentResolver.
                    registerContentObserver(
                            contactsUri,
                            true,
                            new ContactsObserver(new Handler(), activity));
        }
 
AndroidWordLevelSpellCheckerSession(final AndroidSpellCheckerService service) {
    mService = service;
    final ContentResolver cres = service.getContentResolver();

    mObserver = new ContentObserver(null) {
        @Override
        public void onChange(boolean self) {
            mSuggestionsCache.clearCache();
        }
    };
    cres.registerContentObserver(Words.CONTENT_URI, true, mObserver);
}
 
源代码12 项目: TurboLauncher   文件: Launcher.java
/**
 * Registers various content observers. The current implementation registers
 * only a favorites observer to keep track of the favorites applications.
 */
private void registerContentObservers() {
	ContentResolver resolver = getContentResolver();
	resolver.registerContentObserver(
			LauncherProvider.CONTENT_APPWIDGET_RESET_URI, true,
			mWidgetObserver);
}
 
/**
 * This test deletes all records from the weather table using the ContentProvider. It also
 * verifies that registered ContentObservers receive onChange callbacks when data is deleted.
 * <p>
 * It finally queries the ContentProvider to make sure that the table has been successfully
 * cleared.
 * <p>
 * NOTE: This does not delete the table itself. It just deletes the rows of data contained
 * within the table.
 * <p>
 * Potential causes for failure:
 * <p>
 *   1) Within {@link WeatherProvider#delete(Uri, String, String[])}, you didn't call
 *    getContext().getContentResolver().notifyChange(uri, null) after performing a deletion.
 * <p>
 *   2) The cursor returned from the query was null
 * <p>
 *   3) After the attempted deletion, the ContentProvider still provided weather data
 */
@Test
public void testDeleteAllRecordsFromProvider() {

    /*
     * Ensure there are records to delete from the database. Due to our setUp method, the
     * database will not have any records in it when this method is run
     */
    testBulkInsert();

    /*
     * TestContentObserver allows us to test weather or not notifyChange was called
     * appropriately. We will use that here to make sure that notifyChange is called when a
     * deletion occurs.
     */
    TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver();

    /*
     * A ContentResolver provides us access to the content model. We can use it to perform
     * deletions and queries at our CONTENT_URI
     */
    ContentResolver contentResolver = mContext.getContentResolver();

    /* Register a content observer to be notified of changes to data at a given URI (weather) */
    contentResolver.registerContentObserver(
            /* URI that we would like to observe changes to */
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Whether or not to notify us if descendants of this URI change */
            true,
            /* The observer to register (that will receive notifyChange callbacks) */
            weatherObserver);

    /* Delete all of the rows of data from the weather table */
    contentResolver.delete(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null);

    /* Perform a query of the data that we've just deleted. This should be empty. */
    Cursor shouldBeEmptyCursor = contentResolver.query(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null,
            /* Values for "where" clause */
            null,
            /* Sort order to return in Cursor */
            null);

    /*
     * If this fails, it's likely you didn't call notifyChange in your delete method from
     * your ContentProvider.
     */
    weatherObserver.waitForNotificationOrFail();

    /*
     * waitForNotificationOrFail is synchronous, so after that call, we are done observing
     * changes to content and should therefore unregister this observer.
     */
    contentResolver.unregisterContentObserver(weatherObserver);

    /* In some cases, the cursor can be null. That's actually a failure case here. */
    String cursorWasNull = "Cursor was null.";
    assertNotNull(cursorWasNull, shouldBeEmptyCursor);

    /* If the count of the cursor is not zero, all records weren't deleted */
    String allRecordsWereNotDeleted =
            "Error: All records were not deleted from weather table during delete";
    assertEquals(allRecordsWereNotDeleted,
            0,
            shouldBeEmptyCursor.getCount());

    /* Always close your cursor */
    shouldBeEmptyCursor.close();
}
 
/**
 * This test deletes all records from the weather table using the ContentProvider. It also
 * verifies that registered ContentObservers receive onChange callbacks when data is deleted.
 * <p>
 * It finally queries the ContentProvider to make sure that the table has been successfully
 * cleared.
 * <p>
 * NOTE: This does not delete the table itself. It just deletes the rows of data contained
 * within the table.
 * <p>
 * Potential causes for failure:
 * <p>
 *   1) Within {@link WeatherProvider#delete(Uri, String, String[])}, you didn't call
 *    getContext().getContentResolver().notifyChange(uri, null) after performing a deletion.
 * <p>
 *   2) The cursor returned from the query was null
 * <p>
 *   3) After the attempted deletion, the ContentProvider still provided weather data
 */
@Test
public void testDeleteAllRecordsFromProvider() {

    /*
     * Ensure there are records to delete from the database. Due to our setUp method, the
     * database will not have any records in it prior to this method being run.
     */
    testBulkInsert();

    /*
     * TestContentObserver allows us to test weather or not notifyChange was called
     * appropriately. We will use that here to make sure that notifyChange is called when a
     * deletion occurs.
     */
    TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver();

    /*
     * A ContentResolver provides us access to the content model. We can use it to perform
     * deletions and queries at our CONTENT_URI
     */
    ContentResolver contentResolver = mContext.getContentResolver();

    /* Register a content observer to be notified of changes to data at a given URI (weather) */
    contentResolver.registerContentObserver(
            /* URI that we would like to observe changes to */
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Whether or not to notify us if descendants of this URI change */
            true,
            /* The observer to register (that will receive notifyChange callbacks) */
            weatherObserver);

    /* Delete all of the rows of data from the weather table */
    contentResolver.delete(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null);

    /* Perform a query of the data that we've just deleted. This should be empty. */
    Cursor shouldBeEmptyCursor = contentResolver.query(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null,
            /* Values for "where" clause */
            null,
            /* Sort order to return in Cursor */
            null);

    /*
     * If this fails, it's likely you didn't call notifyChange in your delete method from
     * your ContentProvider.
     */
    weatherObserver.waitForNotificationOrFail();

    /*
     * waitForNotificationOrFail is synchronous, so after that call, we are done observing
     * changes to content and should therefore unregister this observer.
     */
    contentResolver.unregisterContentObserver(weatherObserver);

    /* In some cases, the cursor can be null. That's actually a failure case here. */
    String cursorWasNull = "Cursor was null.";
    assertNotNull(cursorWasNull, shouldBeEmptyCursor);

    /* If the count of the cursor is not zero, all records weren't deleted */
    String allRecordsWereNotDeleted =
            "Error: All records were not deleted from weather table during delete";
    assertEquals(allRecordsWereNotDeleted,
            0,
            shouldBeEmptyCursor.getCount());

    /* Always close your cursor */
    shouldBeEmptyCursor.close();
}
 
/**
 * This test deletes all records from the weather table using the ContentProvider. It also
 * verifies that registered ContentObservers receive onChange callbacks when data is deleted.
 * <p>
 * It finally queries the ContentProvider to make sure that the table has been successfully
 * cleared.
 * <p>
 * NOTE: This does not delete the table itself. It just deletes the rows of data contained
 * within the table.
 * <p>
 * Potential causes for failure:
 * <p>
 *   1) Within {@link WeatherProvider#delete(Uri, String, String[])}, you didn't call
 *    getContext().getContentResolver().notifyChange(uri, null) after performing a deletion.
 * <p>
 *   2) The cursor returned from the query was null
 * <p>
 *   3) After the attempted deletion, the ContentProvider still provided weather data
 */
@Test
public void testDeleteAllRecordsFromProvider() {

    /*
     * Ensure there are records to delete from the database. Due to our setUp method, the
     * database will not have any records in it prior to this method being run.
     */
    testBulkInsert();

    /*
     * TestContentObserver allows us to test weather or not notifyChange was called
     * appropriately. We will use that here to make sure that notifyChange is called when a
     * deletion occurs.
     */
    TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver();

    /*
     * A ContentResolver provides us access to the content model. We can use it to perform
     * deletions and queries at our CONTENT_URI
     */
    ContentResolver contentResolver = mContext.getContentResolver();

    /* Register a content observer to be notified of changes to data at a given URI (weather) */
    contentResolver.registerContentObserver(
            /* URI that we would like to observe changes to */
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Whether or not to notify us if descendants of this URI change */
            true,
            /* The observer to register (that will receive notifyChange callbacks) */
            weatherObserver);

    /* Delete all of the rows of data from the weather table */
    contentResolver.delete(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null);

    /* Perform a query of the data that we've just deleted. This should be empty. */
    Cursor shouldBeEmptyCursor = contentResolver.query(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null,
            /* Values for "where" clause */
            null,
            /* Sort order to return in Cursor */
            null);

    /*
     * If this fails, it's likely you didn't call notifyChange in your delete method from
     * your ContentProvider.
     */
    weatherObserver.waitForNotificationOrFail();

    /*
     * waitForNotificationOrFail is synchronous, so after that call, we are done observing
     * changes to content and should therefore unregister this observer.
     */
    contentResolver.unregisterContentObserver(weatherObserver);

    /* In some cases, the cursor can be null. That's actually a failure case here. */
    String cursorWasNull = "Cursor was null.";
    assertNotNull(cursorWasNull, shouldBeEmptyCursor);

    /* If the count of the cursor is not zero, all records weren't deleted */
    String allRecordsWereNotDeleted =
            "Error: All records were not deleted from weather table during delete";
    assertEquals(allRecordsWereNotDeleted,
            0,
            shouldBeEmptyCursor.getCount());

    /* Always close your cursor */
    shouldBeEmptyCursor.close();
}
 
源代码16 项目: Study_Android_Demo   文件: SettingsProviderTest.java
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);
    }
}
 
/**
 * Tests deleting a single row of data via a ContentResolver
 */
@Test
public void testDelete() {
    /* Access writable database */
    TaskDbHelper helper = new TaskDbHelper(InstrumentationRegistry.getTargetContext());
    SQLiteDatabase database = helper.getWritableDatabase();

    /* Create a new row of task data */
    ContentValues testTaskValues = new ContentValues();
    testTaskValues.put(TaskContract.TaskEntry.COLUMN_DESCRIPTION, "Test description");
    testTaskValues.put(TaskContract.TaskEntry.COLUMN_PRIORITY, 1);

    /* Insert ContentValues into database and get a row ID back */
    long taskRowId = database.insert(
            /* Table to insert values into */
            TaskContract.TaskEntry.TABLE_NAME,
            null,
            /* Values to insert into table */
            testTaskValues);

    /* Always close the database when you're through with it */
    database.close();

    String insertFailed = "Unable to insert into the database";
    assertTrue(insertFailed, taskRowId != -1);


    /* TestContentObserver allows us to test if notifyChange was called appropriately */
    TestUtilities.TestContentObserver taskObserver = TestUtilities.getTestContentObserver();

    ContentResolver contentResolver = mContext.getContentResolver();

    /* Register a content observer to be notified of changes to data at a given URI (tasks) */
    contentResolver.registerContentObserver(
            /* URI that we would like to observe changes to */
            TaskContract.TaskEntry.CONTENT_URI,
            /* Whether or not to notify us if descendants of this URI change */
            true,
            /* The observer to register (that will receive notifyChange callbacks) */
            taskObserver);



    /* The delete method deletes the previously inserted row with id = 1 */
    Uri uriToDelete = TaskContract.TaskEntry.CONTENT_URI.buildUpon().appendPath("1").build();
    int tasksDeleted = contentResolver.delete(uriToDelete, null, null);

    String deleteFailed = "Unable to delete item in the database";
    assertTrue(deleteFailed, tasksDeleted != 0);

    /*
     * If this fails, it's likely you didn't call notifyChange in your delete method from
     * your ContentProvider.
     */
    taskObserver.waitForNotificationOrFail();

    /*
     * waitForNotificationOrFail is synchronous, so after that call, we are done observing
     * changes to content and should therefore unregister this observer.
     */
    contentResolver.unregisterContentObserver(taskObserver);
}
 
/**
 * This test deletes all records from the weather table using the ContentProvider. It also
 * verifies that registered ContentObservers receive onChange callbacks when data is deleted.
 * <p>
 * It finally queries the ContentProvider to make sure that the table has been successfully
 * cleared.
 * <p>
 * NOTE: This does not delete the table itself. It just deletes the rows of data contained
 * within the table.
 * <p>
 * Potential causes for failure:
 * <p>
 *   1) Within {@link WeatherProvider#delete(Uri, String, String[])}, you didn't call
 *    getContext().getContentResolver().notifyChange(uri, null) after performing a deletion.
 * <p>
 *   2) The cursor returned from the query was null
 * <p>
 *   3) After the attempted deletion, the ContentProvider still provided weather data
 */
@Test
public void testDeleteAllRecordsFromProvider() {

    /*
     * Ensure there are records to delete from the database. Due to our setUp method, the
     * database will not have any records in it prior to this method being run.
     */
    testBulkInsert();

    /*
     * TestContentObserver allows us to test weather or not notifyChange was called
     * appropriately. We will use that here to make sure that notifyChange is called when a
     * deletion occurs.
     */
    TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver();

    /*
     * A ContentResolver provides us access to the content model. We can use it to perform
     * deletions and queries at our CONTENT_URI
     */
    ContentResolver contentResolver = mContext.getContentResolver();

    /* Register a content observer to be notified of changes to data at a given URI (weather) */
    contentResolver.registerContentObserver(
            /* URI that we would like to observe changes to */
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Whether or not to notify us if descendants of this URI change */
            true,
            /* The observer to register (that will receive notifyChange callbacks) */
            weatherObserver);

    /* Delete all of the rows of data from the weather table */
    contentResolver.delete(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null);

    /* Perform a query of the data that we've just deleted. This should be empty. */
    Cursor shouldBeEmptyCursor = contentResolver.query(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null,
            /* Values for "where" clause */
            null,
            /* Sort order to return in Cursor */
            null);

    /*
     * If this fails, it's likely you didn't call notifyChange in your delete method from
     * your ContentProvider.
     */
    weatherObserver.waitForNotificationOrFail();

    /*
     * waitForNotificationOrFail is synchronous, so after that call, we are done observing
     * changes to content and should therefore unregister this observer.
     */
    contentResolver.unregisterContentObserver(weatherObserver);

    /* In some cases, the cursor can be null. That's actually a failure case here. */
    String cursorWasNull = "Cursor was null.";
    assertNotNull(cursorWasNull, shouldBeEmptyCursor);

    /* If the count of the cursor is not zero, all records weren't deleted */
    String allRecordsWereNotDeleted =
            "Error: All records were not deleted from weather table during delete";
    assertEquals(allRecordsWereNotDeleted,
            0,
            shouldBeEmptyCursor.getCount());

    /* Always close your cursor */
    shouldBeEmptyCursor.close();
}
 
private MobileContactSingleton() {
    Log.d("hyh", "MobileContactSingleton: MobileContactSingleton: 实例化");
    mMobileContactObserver = new MobileContactObserver(null);
    ContentResolver contentResolver = MyApplication.getApplication().getContentResolver();
    contentResolver.registerContentObserver(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,false,mMobileContactObserver);
}
 
/**
 * Tests inserting a single row of data via a ContentResolver
 */
@Test
public void testInsert() {

    /* Create values to insert */
    ContentValues testTaskValues = new ContentValues();
    testTaskValues.put(TaskContract.TaskEntry.COLUMN_DESCRIPTION, "Test description");
    testTaskValues.put(TaskContract.TaskEntry.COLUMN_PRIORITY, 1);

    /* TestContentObserver allows us to test if notifyChange was called appropriately */
    TestUtilities.TestContentObserver taskObserver = TestUtilities.getTestContentObserver();

    ContentResolver contentResolver = mContext.getContentResolver();

    /* Register a content observer to be notified of changes to data at a given URI (tasks) */
    contentResolver.registerContentObserver(
            /* URI that we would like to observe changes to */
            TaskContract.TaskEntry.CONTENT_URI,
            /* Whether or not to notify us if descendants of this URI change */
            true,
            /* The observer to register (that will receive notifyChange callbacks) */
            taskObserver);


    Uri uri = contentResolver.insert(TaskContract.TaskEntry.CONTENT_URI, testTaskValues);


    Uri expectedUri = ContentUris.withAppendedId(TaskContract.TaskEntry.CONTENT_URI, 1);

    String insertProviderFailed = "Unable to insert item through Provider";
    assertEquals(insertProviderFailed, uri, expectedUri);

    /*
     * If this fails, it's likely you didn't call notifyChange in your insert method from
     * your ContentProvider.
     */
    taskObserver.waitForNotificationOrFail();

    /*
     * waitForNotificationOrFail is synchronous, so after that call, we are done observing
     * changes to content and should therefore unregister this observer.
     */
    contentResolver.unregisterContentObserver(taskObserver);
}