简体   繁体   中英

Android Long Running Service and database

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM