3
我只是想了解android服务和内容观察者。android注册到服务的内容观察者
因此,我尝试了一个程序,在该程序中,我的活动启动了一项服务,并在服务范围内向联系人URI注册,以便在联系人数据库更改时得到通知。
我朗姆酒我的程序,我可以看到这个服务应用程序 - >正在运行的服务。 现在我尝试添加联系人,并且我的观察者正在收到通知。 如果我再次编辑联系人,它没有得到通知。运行我的程序后,如果我编辑联系人它仅在第一次,内容观察者得到通知 请参考下面
Mainactivity我的代码细节来启动服务:
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 2013-03-29 12:22:57