Alternative to using Handler in a service
I am working on an application which needs to do a WiFi scan every 5-6 seconds. WiFiScanner class is implemented as a service and called from the main Activity. In order to repea开发者_JAVA百科t tasks every few seconds, I have used Handler with postDelayed with an interval of 5000 msecs. After installing on the device the application runs fine first time. Stopping the WiFi scan process, closing and immediately reopening the application causes it to crash. I suppose its because I haven't stopped the Handler explicitly in the main activity by calling removecallbacks on the runnable, instead clicking stop would simply stop the service. Here's what logcat throws on the error.
06-14 12:30:58.181: ERROR/AndroidRuntime(23534): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.wifi.SCAN_RESULTS } in com.test.example.WiFiScanner$1@2b0a3880
I was looking through stackoverflow and found suggestions to use an AlarmManager instead. But wouldn't this require me to implement a BroadcastReciever class for the purpose as it says here? Is there any other alternative to Handler to doing repetitive tasks in a service invoked from the Main Activity?
well you can just bind the service instead of starting it. that means it's a local service which will get stopped when there arent any more activities bound to it. but be carefull because the service runs in the ui thread so move things in a background thread. what i have commonly used in situations like this is a handler that postDelayed a runnable executing an async task where you can do whatever you want to do and then rescheduling it so it runs in some time period. also remove the callbacks when the service is destroyed and start it sticky so that if it is killed it restarts and you can also remove the callbacks on start.
As an alternative you can use an intent service or a simple service with alarms that is started by the alarm on specific time periods, that calls selfStop after it has completed a scan. but if you are running frequent checks then this creates an overhead because the service needs to be created over and over again (so better keep it running then).
there is also the timerTask class but i simply find this 2 solutions better. the timer class introduces a new thread
see: Timer
And This for an implementation
and here is someone that tried to do the same thing as you are:
Timer task and answers
精彩评论