I am building an app which will monitor the battery state, wifi connection and location data at regular intervals and will write the results in a file (and later send them off to a server). On installing the app monitoring should be disabled - but the user enabling it should survive a reboot. After a lot of reading I have realized that I have basically 2 options :
- Subclass
Service
and fire it off from my activity. Set it on foreground, STICKY and what not and hope that it is not killed by android - and take care if android recreates it (actually there should be 3 services so syncing between them could be messy). Start a thread in the service (no need for Executors I guess) and have itThread.sleep(REGULAR_INTERVAL)
. Wake up, collect the data write them to a file. Broadcast the collected info and display it on my activity if it happens to be running (which will have registered a Broadcast Receiver). Rinse and repeatwhile(true)
. Have a way to interrupt this - Have my activity register a PendingIntent with AlarmManager - which will run every REGULAR_INTERVAL. I haven't looked into the technical details of this approach so much - but I hope I will be able to make this PendingIntent create and run an IntentService (this seems the way to go - having the Thread machinery for free as well as shutting down on its own). Some skeleton code for this approach would be welcome.
I think I have to register a boot receiver in both cases to check the Shared Preferences (have already done this) and in case 1 start the service(s) while in case 2 register a Receiver for the alarm event and set the alarm manager up - that is the part I need some skeleton code.
So - before I start building this - which would be the preferred approach ?
In recap - the app should monitor some phone properties and write them to a file till the user chooses to shut it off.