我想实现一个BroadcastReceiver
来监听联系人是否已被删除/更新。我读到了ContantObserver
,但我不知道如何在应用程序背景中运行它,例如BroadcastReceiver
。
我该如何实现?有没有办法在应用程序的后台运行ContantObserver
。
我关注this FAQ.
答案 0 :(得分:0)
实施广播接收器并使用onChange
ContentObserver
方法发送广播以定位此接收器..请参阅this以了解使用自定义意图和广播IP>
答案 1 :(得分:0)
启动服务并将ContentObserver注册到此服务器
以下是我所做的示例代码,它将侦听Contacts.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);
}
}