0

BroadcastReceiver如果联系人已被删除/更新,我想实现一个监听。我读过ContantObserver但我不知道如何在应用程序后台运行它,比如BroadcastReceiver.

我该如何实施?有什么方法可以ContantObserver在应用程序的后台运行。

我遵循了这个常见问题解答。

4

2 回答 2

0

实现一个广播接收器并在定位这个接收器的onChange方法中发送广播ContentObserver.. 看到这个使用自定义意图和广播..

于 2012-04-18T12:39:17.073 回答
0

启动服务并将 ContentObserver 注册到此服务器

这是我所做的示例代码,它将监听 Co​​ntacts.CONTENT_URI 中的任何更改并通知用户

这是服务

public class ContactObserverService extends Service implements ContactObserver.OnUpdate {
private ContactObserver contactObserver ;

public ContactObserverService() {
}

@Override
public void onCreate(){
    super.onCreate();
    contactObserver = new ContactObserver(this);
    Toast.makeText(this,"Service Started",Toast.LENGTH_SHORT).show();
    this.getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI,false,contactObserver);
}

@Override
public void onDestroy() {
    if( contactObserver !=null  )
    {
        this.getContentResolver().unregisterContentObserver(contactObserver);
    }
    super.onDestroy();
}

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // The service is starting, due to a call to startService()
    return START_STICKY;
}

@Override
public void onUpdate(Uri uri) {
    NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
            .setContentTitle("Contact Update Notifier")
            .setContentText(uri.getQuery())
            .setSmallIcon(R.drawable.images);
    NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    manager.notify(1,builder.build());
}
}

ContentObserver 类是

public class ContactObserver extends ContentObserver {
private OnUpdate onUpdate;

public interface OnUpdate{
    void onUpdate(Uri uri);
}
public ContactObserver(OnUpdate onUpdate) {
    super(new Handler());
    this.onUpdate = onUpdate;
}

@Override
public void onChange(boolean selfChange) {
    this.onChange(selfChange, null);
}
@Override
public void onChange(boolean selfChange, Uri uri) {
    // this is NOT UI thread, this is a BACKGROUND thread
    uri.getQueryParameterNames();
    onUpdate.onUpdate(uri);
}
}
于 2016-08-09T07:44:35.620 回答