Android服务中注册内容观察器

3
我只是想了解安卓服务和内容观察者。因此,我尝试编写一个程序,在其中我的活动启动了一个服务,并在服务中注册了CONTACTS URI,以便在联系人数据库更改时得到通知。
我运行我的程序,可以看到这个服务出现在“应用程序”->“正在运行的服务”下。现在我试图添加一个联系人,我的观察者会收到通知。如果我再次编辑联系人,则不会收到通知。只有在运行我的程序后第一次编辑联系人时,内容观察者才会被通知。 请参见下面的代码详细信息。
主要活动来启动服务:
public class ContactChangeOberverServiceActivity extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.i("Start","Service");
        startService(new Intent(this, MyService.class));
    }
}

服务:

public class MyService extends Service {

    private static final String TAG = "MyService";

    @Override
    public void onCreate() {
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStart");
        ContactObserverActivity observer = new ContactObserverActivity(new Handler());
        observer.register(getApplicationContext());
        return  super.onStartCommand(intent, flags, startId);
    }

    public boolean deliverSelfNotifications() {
        return true;
    }
}

观察者是:

@Override
public void onChange(boolean selfChange) {
    // TODO Auto-generated method stub
    // super.onChange(selfChange);
    Log.e(TAG, "Onchange Called");
    //MainActivity.takeContactBackup();
    Intent intent = new Intent (ctx,ContactsExtractorActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    ctx.startActivity(intent);
}

/ TODO Auto-generated constructor stub
}

public void register(Context ctx) {
    Log.e(TAG, "Registering");
    this.ctx = ctx;
    curval = ctx.getContentResolver().query(
            ContactsContract.Contacts.CONTENT_URI, projection, null, null,
            null);
    curval.registerContentObserver(new ContactObserverActivity(
            new Handler()));
    Log.e(TAG, "Registered");
}

请帮我理解这种行为以及如何修复。谢谢。


我也有同样的问题,你解决了吗? - PrvN
1个回答

0

使用此URI:

ContactsContract.CommonDataKinds.Phone.CONTENT_URI

对我有用!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接