安卓:内容观察者的"的onChange()"方法被调用多次观察者、方法、内容、QUOT

2023-09-06 13:13:18 作者:好小伙潇潇洒酒@

我使用的是内容观察员内容://短信。我写的所有消息在SD卡上的文本文件。但在内容观察员的onChange()方法被调用多次和相同的信息写入多次到文本文件中。如何避免这种情况?此外,我想知道,如果有内容的观察者会拖慢手机。

I am using a content observer for content://sms. I am writing all the messages to a text file in SD card. But the onChange() method in the content observer is called multiple times and the same message is written multiple times to the text file. How to avoid this? Also I want to know if having the content observer will slow down the phone.

推荐答案

您需要重写deliverSelfNotifications()返回true。

You need to override deliverSelfNotifications() to return true.

class ObserverSms extends ContentObserver {
private Context mContext;

public ObserverSms(Context context, Handler handler) {
    super(handler);
    mContext = context;
}

@Override
public boolean deliverSelfNotifications() {
    return true;
}

@Override
public void onChange(boolean selfChange) {
    super.onChange(selfChange);
    MyLog.logDebugInConsole(TAG, "Sms Database Changed");
}
}