内容提供者和内容观察者示例?
我是 Android 开发新手,并且与内容提供商和内容观察者打交道。但是我在网上找不到例子。我一直在玩和阅读有关此内容的内容,但陷入了困境。这就是我想要做的:
我创建了一个小型内容提供程序(我已确认该内容提供程序正在工作并在手机上的数据库中插入/删除数据)。我们将其称为 A.apk。现在我想创建一个 B.apk,对数据库进行的任何更新都会通知该 B.apk。因此,如果创建了新内容,B 将显示它,如果内容被删除,它将从 B 的视图中删除。
我陷入困境,很想看看如何使用最佳实践正确完成此操作。一个例子将不胜感激!
I am new to Android development and playing with content providers and content observers. However I am having trouble finding examples online. I have been playing and reading about this but have become stuck. Here is what I am trying to do:
I have created a small content provider (that I have confirmed is working and inserting/deleting data in a db on the phone). We will call this A.apk. Now I want to create a B.apk that will be notified with any updates done to the db. So if new content is created B will display it and if content is delete it will be removed from B's view.
I am stuck and would love to see how this is done correctly using best practices. An example would be much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这其实很简单。
只需实现一个 ContentObserver 并将其注册到要监视的数据库的 URI 即可。示例中,当A使用B的ContentProvider将数据放入B定义的数据库时,会触发B的ContentObserver的onChange()方法。但是,如果进行更改时 B 没有运行,就会出现问题。
另一种解决方案是 A 使用 B 的 ContentProvider 向 B 的数据库插入数据,然后向 B 发送新数据正在等待的 Intent。
或者在 B 的 ContentProvider 的实现中,它可以启动属于 B 的 Activity。
根据应用程序的需求和关注点来确定使用哪种方法。
This is actually very easy.
Just implement a ContentObserver and register it with the URI of the database to watch. In the example about when A uses B's ContentProvider to put data into B's defined database, B's ContentObserver's onChange() method will be triggered. There is a problem however if B is not running when a change is made.
Another solution is for A to use B's ContentProvider to insert data into B's database, then send an intent to B that new data is waiting.
Or in the implementation of B's ContentProvider it could start and Activity belonging to B.
Depending on what the application's needs and concerns are will determine which method to use.