Reputation: 522
I am implementing a Service that starts when Android boots, and it's supposed to scan every 10 mins for nearby Bluetooth devices. When it discovers devices, it does some work. Also, this periodic scanning should occur the entire time the device is on. I am trying to schedule a TimerTask, but I don't understand how to use it. I guess it should start this service and let the service do the work instead of writing the code in the TimerTask's run method? How would I start the service from the TimerTask as this seems the easiest way to remedy my problem, but TimerTask is part of java.util and not one of Android's classes.
I just found Android's AlarmManager. Should I use that? Can it start a Service?
So far I have this, but I need help:
class Timer extends Service { private Handler myHander;Runnable r = new Runnable() { run() { startService(new Intent(Timer.this.getApplicationContext() ,MyService.class));
myHandler.postDelayed(r,10 minutes); } }
onCreate() { myHandler=new MyHandler(); } onStartCommand() { //Do the bluetooth work.
r.run(); }
onDestroy() { super.onDestroy(); myHandler.removeCallback(r); }
} class MyService extends Service { }
Sorry, I don't understand how the formatting works here.
Will I need to override onDestroy() in the Service? Where to do I use stopService() ?
Upvotes: 0
Views: 803
Reputation: 74780
You need to:
onStart
/onStartCommand
you need to schedule either using Handler
or AlaramManager
periodic updates.The difference between Handler
and AlarmManager
in this case will be that: Handler
will not run when device is in deep sleep, while you can configure AlaramManager
to wake up the device and run your code.
I'd recommend to go with Handler
, as its easier and because you said you only need to run your code when device is awake.
And one more thing, Handler
doesn't use extra thread while TimerTask
does. And this is considered a bad practice on Android to waste on thread for timer only.
An example code for how to repeat task using Handler
can be found here: Repeat a task with a time delay?.
Upvotes: 0