Android 长时间运行服务和数据库
我正在开发一个由两部分组成的程序
服务组件 将在每个预定的时间间隔读取各种系统功能(CPU 使用情况、RAM 使用情况、正在运行的任务数、发送的消息、拨打的电话等)说15分钟。并将这些读数/数据保存在数据库中。
活动组件将从SQL数据库文件中读取数据并处理信息。
我的问题是
我必须创建什么样的服务才能永远保持活动状态,直到被活动停止为止,它还应该在系统重新启动后自动重新启动?
有人有将数据写入数据库的服务示例吗?
我可以从服务调用父活动吗?
I am working on a program which consists of two parts
Service component will read various system features (CPU usage, RAM usage, Number of Running Tasks, Messages Sent, Calls Made etc) every pre determined time interval lets say 15 minutes. And save these readings/data in a database.
Activity component will read the data from SQL database file and process the information.
My Questions are
What kind of service do I have to create that will stay alive forever until stopped by the activity it should also automatically restart after system reboot?
Has anyone got an example of service writing data to database?
Can I invoke the parent activity from the service?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来像是一个相当标准的
服务
。阅读Service
生命周期。回答:
BroadcastReceiver
来侦听BOOT_COMPLETED
意图,以便在启动时启动服务。Service
对象是Context
对象,因此您可以使用 SQLite 数据库执行任何可以在Activity
中执行的操作。没有区别。Context
中的标准startActivity()
方法从服务启动Activity
。如果您在启动时从BroadcastReceiver
启动Service
,则它是一个独立的服务,未连接到任何Activity
,因此没有父Activity
。另请注意,对于您所声明的意图而言,
服务
可能并非绝对必要。如果您只做不常做的事情,您也许可以使用AlarmManager
闹钟来应付。这样,您就不会为了每 15 分钟才处理一次的事情而让Service
继续运行并消耗资源。Sounds like a fairly standard
Service
. Read up on theService
lifecycle.Answers:
BroadcastReceiver
that listens for theBOOT_COMPLETED
intent to start the service at boot.Service
objects areContext
objects, so you can do anything with a SQLite database that you could do from anActivity
. No difference.Activity
from the service via the standardstartActivity()
method fromContext
. If you start theService
from theBroadcastReceiver
at boot, it's an independent service not connected to anyActivity
so there is no parentActivity
.Note also that a
Service
may not be absolutely necessary for your stated intent. If you're only doing things that infrequently, you may be able to get by with anAlarmManager
alarm. That way you're not leaving aService
running -- and consuming resources -- for something you're only processing every 15 minutes.