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