gpt4 book ai didi

android从服务注册到内容观察者

转载 作者:太空狗 更新时间:2023-10-29 15:18:36 26 4
gpt4 key购买 nike

我只是想了解 android 服务和内容观察器。

因此,我尝试了一个程序,在该程序中,我的 Activity 启动了一项服务,并在服务中注册了 CONTACTS URI,以便在联系人数据库发生变化时收到通知。

我朗读我的程序,我可以看到该服务位于应用程序 -> 运行服务下。现在我尝试添加一个联系人,我的观察者收到了通知。如果我再次编辑联系人,则不会收到通知。如果我编辑联系人,这只是在运行我的程序后第一次,内容观察者收到通知请在下面查看我的代码详细信息

启动服务的主要 Activity :

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");
}

请帮助我理解此行为及其修复方法。谢谢。

最佳答案

使用这个 URI:

ContactsContract.CommonDataKinds.Phone.CONTENT_URI

对我有用!

关于android从服务注册到内容观察者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10122077/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com