Update data in Background Periodically (Android)

2020-04-14 16:31发布

问题:

The main objective of my app is, when a button is pressed:

  1. Collect data from the sensors
  2. Store data in the database
  3. 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, crashes
  • Intent 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.

回答1:

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.