how to keep an Intent service running

随声附和 提交于 2019-11-29 09:42:02

问题


I have two examples of Intentservice. One is the Download example in the commonsware book. the other is at http://www.vogella.com/articles/AndroidServices/article.html#servicecommunication_handler. Both of these examples show the service executing a finite task and they both apparently destroy themselves by running to the end of the scope of the onHandleIntent event.

The service I am writing has to have events and listen for things. One is a LocationListener listening for GPS movement. Another makes Posts to a REST service and listens for replys. I want it to run until a time has elapsed or until it was told to quit by the activity that started it.

How do I keep it running? Where, for instance, do I put my implementation of LocationListener? Thanks, Gary


回答1:


How do I keep it running?

You don't. IntentService is designed to do a piece of work (or perhaps a few off a queue, if commands happen to come in rapidly), then shut down.

The service I am writing has to have events and listen for things.

Then you should not be using an IntentService. Use a regular Service, with your own background thread(s) as needed.




回答2:


To keep a service running, your service need to return START_STICKY in the service method onStartCommand().

With this, the service will be running even if you exit form your activity.

Note: The Android still kills services after some time (30 mintus to 1 hour) if they are not foreground services. Use startForeground(notification) to make it foreground.

good luck




回答3:


You can achieve this in either of two ways,

  • AlarmManager
  • TimerTask

AlarmManager is android's in-buite class that allows you to execute certain action on particular time peroid.

TimerTask does same thing as AlarmManager, you can repeat certain action of your code again and again.

However AlarmManager is ligher in the execution so i suggest you to go with AlarmManager class.

Create an AlarmManager that fetches the GPS Co-ordinates and post them to server on regular interval basis.

Have a look at to this AlarmManager Example.



来源:https://stackoverflow.com/questions/12878150/how-to-keep-an-intent-service-running

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