Android 长时间运行服务和数据库

发布于 2025-01-04 14:55:23 字数 350 浏览 0 评论 0原文

我正在开发一个由两部分组成的程序

服务组件 将在每个预定的时间间隔读取各种系统功能(CPU 使用情况、RAM 使用情况、正在运行的任务数、发送的消息、拨打的电话等)说15分钟。并将这些读数/数据保存在数据库中。

活动组件将从SQL数据库文件中读取数据并处理信息。

我的问题是

  1. 我必须创建什么样的服务才能永远保持活动状态,直到被活动停止为止,它还应该在系统重新启动后自动重新启动?

  2. 有人有将数据写入数据库的服务示例吗?

  3. 我可以从服务调用父活动吗?

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

  1. 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?

  2. Has anyone got an example of service writing data to database?

  3. Can I invoke the parent activity from the service?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

依 靠 2025-01-11 14:55:23

听起来像是一个相当标准的服务。阅读Service 生命周期

回答:

  1. 任何服务都可以。您需要一个 BroadcastReceiver 来侦听 BOOT_COMPLETED 意图,以便在启动时启动服务。
  2. Service 对象是 Context 对象,因此您可以使用 SQLite 数据库执行任何可以在 Activity 中执行的操作。没有区别。
  3. 定义“调用”和“父活动”。您可以通过 Context 中的标准 startActivity() 方法从服务启动 Activity。如果您在启动时从 BroadcastReceiver 启动 Service,则它是一个独立的服务,未连接到任何 Activity,因此没有父 Activity

另请注意,对于您所声明的意图而言,服务可能并非绝对必要。如果您只做不常做的事情,您也许可以使用 AlarmManager 闹钟来应付。这样,您就不会为了每 15 分钟才处理一次的事情而让 Service 继续运行并消耗资源。

Sounds like a fairly standard Service. Read up on the Service lifecycle.

Answers:

  1. Any service will do. You'll need a BroadcastReceiver that listens for the BOOT_COMPLETED intent to start the service at boot.
  2. Service objects are Context objects, so you can do anything with a SQLite database that you could do from an Activity. No difference.
  3. Define "invoke" and "parent activity". You can start an Activity from the service via the standard startActivity() method from Context. If you start the Service from the BroadcastReceiver at boot, it's an independent service not connected to any Activity so there is no parent Activity.

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 an AlarmManager alarm. That way you're not leaving a Service running -- and consuming resources -- for something you're only processing every 15 minutes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文