The main objective of my app is, when a button is pressed:
- Collect data from the sensors
- Store data in the database
- Repeat periodically (every X seconds)
I want to have it done in background, and if the Main Activity
is destroyed, the background progress to be still running. So if you delete the activity, I want it still running.
What I am doing right now, is having an AlarmManager
with an Intent Service
, to set the periodic recording of the Data, but whenever I destroy the Activity
, as they are related, my app crashes.
I know there are different to run a background process, but none fits in mine:
Service
: Depends on MainThread, so if the MainActivity is destroyed, crashesIntent Service
: The one using right now, but as far as it is related to AlarmManager, that is related to MainActivity, when it is destroyed, crashes.AsyncTask
: The problem of this one, is that it is supposed to do one task in background and it finishes, but what I really want is to do it periodically until the user says to stop. So it's not a matter of one time thing.
Is there any other way to have a background service? Can any of the stated before be used for my purpose? How do you recommend me to do it?
Thanks for your answers.
Try to start service in separate process using
android:process=":servicename"
in AndroidManifest.xml. If service is running in another process, it wouldn't be killed with activity.