正确的方法从两个活动和服务启动Access数据库? [英] proper way to access DB from both Activity and a started Service?

查看:172
本文介绍了正确的方法从两个活动和服务启动Access数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

短版:?什么是最好的实践方法,从两个活动,并开始从服务访问同一个数据库

Short version: what is the best practice way to access the same DB from both activity and from started service?

龙版:我有我的地方,从活动开始持续服务的情况。服务与数据填充数据库,而活动显示在屏幕上。他们都不是运行所有的时间 - 当没有活动服务​​可以运行,而当服务尚未启动活动可以运行。但服务只能从活动停止(它从不停止本身)。

Long version: I have a case where I start persistent service from activity. Service is populating the DB with data while activity is displaying it on screen. Neither of them is running all the time - service can run when there is no activity, and activity can run when service is not started yet. But service can only be stopped from activity (it never stops itself).

我使用SQLiteOpenHelper的子类来访问数据库。我绊倒的问题是,显然收盘DB在一个 SQLiteOpenHelper 实例关闭它在另一个太

I am using subclass of SQLiteOpenHelper to access the DB. The problem I tripped over is that apparently closing DB in one SQLiteOpenHelper instance closes it in another too.

我能想到的这些选项:


  1. 单件模式(单 SQLiteDatabase 在一个公共静态无功实例 - 唯一的活动可以关闭它(因为它或者知道,如果服务正在运行不)) - 丑

  2. 检查服务/活动在另一个关闭之前运行 - 丑

  3. 打造采集/释放到SQLiteOpenHelper的 getReadableDatabase() / 的close()

  1. singleton pattern (single SQLiteDatabase instance in a public static var - only activity can close it (because it knows if the service is running or not)) - ugly
  2. check if service/activity is running before closing it in the other one - ugly
  3. build acquire/release into SQLiteOpenHelper's getReadableDatabase()/close()

我会去3,但是这必须是一个很常见的模式,所以我想知道如果有一个地方这样一个内置的机制已经 - 我讨厌推倒重来。

I would go with 3., but this must be a very common pattern, so I'm wondering if there is such a built-in mechanism in place already - I'd hate to reinvent the wheel.

在换句话说,什么是正确的方式做到这一点?

In other words, what would be the proper way to do it?

推荐答案

有关Android的任何数据库通常的模式是有一个供应商打开数据库,并处理请求的意图。这具有序列请求的优点。

The usual paradigm for any database on Android is to have one provider open the database and handle requests as intents. This has the advantage of serializing requests.

打开数据库完全是非标准的。

Opening databases from different code is completely non-standard.

如果你真的需要一个应用程序每次添加的东西时要注意,从提供广播意图可能是答案。

If you really need an app to notice each time something is added, a broadcast intent from the provider might be the answer.

这篇关于正确的方法从两个活动和服务启动Access数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆