Update data in Background Periodically (Android)

非 Y 不嫁゛ 提交于 2019-12-31 03:00:39

问题


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.



来源:https://stackoverflow.com/questions/23513114/update-data-in-background-periodically-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!