如何知道哪个特定的联系人已在android中更新? [英] How to know which specific contact was updated in android?

查看:88
本文介绍了如何知道哪个特定的联系人已在android中更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够获得通用通知联系人数据库已更改,但是我想知道插入,更新或删除的特定记录。

I am able to get a generic notification "that there was a change to the contacts DB", but I want to know the specific record that was inserted, updated, or deleted.

我不想使用查找URI概念,因为我不想为每个联系人单独设置查找URI。我想要一个通用的解决方案,我可以在任何联系人被更新或删除时知道。

I don't want to use Look-up URI concept because I don't want to set look-up URI for every contact individually. I want a generic solution that I can know when any contact is updated or deleted.

推荐答案

您可以实现 Service 来监视数据库状态。

You can implement an Service to watch the database status.

import android.app.Service;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Handler;
import android.os.IBinder;
import android.provider.ContactsContract;

public class ContactService extends Service {

private int mContactCount;

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
    mContactCount = getContactCount();
    this.getContentResolver().registerContentObserver(
            ContactsContract.Contacts.CONTENT_URI, true, mObserver);
}

private int getContactCount() {
    Cursor cursor = null;
    try {
        cursor = getContentResolver().query(
                ContactsContract.Contacts.CONTENT_URI, null, null, null,
                null);
        if (cursor != null) {
            return cursor.getCount();
        } else {
            return 0;
        }
    } catch (Exception ignore) {
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return 0;
}

private ContentObserver mObserver = new ContentObserver(new Handler()) {

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);

        final int currentCount = getContactCount();
        if (currentCount < mContactCount) {
            // DELETE HAPPEN.
        } else if (currentCount == mContactCount) {
            // UPDATE HAPPEN.
        } else {
            // INSERT HAPPEN.
        }
                    mContactCount = currentCount;
    }

};

    @Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    getContentResolver().unregisterContentObserver(mObserver);
 }

}

这篇关于如何知道哪个特定的联系人已在android中更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆