I'm developing an Android 2.3.3 application and I need to run a method every X seconds.
In iOS, I have NSTimer, but in Android I don't know what to use.
Someone have recommend me Handler; another recommend me AlarmManager but I don't know which method fits better with NSTimer.
This is the code I want to implement in Android:
timer2 = [
NSTimer scheduledTimerWithTimeInterval:(1.0f/20.0f)
target:self
selector:@selector(loopTask)
userInfo:nil
repeats:YES
];
timer1 = [
NSTimer scheduledTimerWithTimeInterval:(1.0f/4.0f)
target:self
selector:@selector(isFree)
userInfo:nil
repeats:YES
];
I need something what works like NSTimer.
What do you recommend me?
If you are familiar with RxJava, you can use Observable.interval(), which is pretty neat.
The downside of this is that you have to architect polling your data in a different way. However, there are a lot of benefits to the Reactive Programming way:
With RxAndroid, you can handle threads in just 2 lines of code.
Please check out RxJava. It has a high learning curve but it will make handling asynchronous calls in Android so much easier and cleaner.
Here I used a thread in onCreate() an Activity repeatly, timer does not allow everything in some cases Thread is the solution
In case it needed it can be stoped by
Use Timer for every second...
try this code to call handler every 15 seconds and stop it when activity not visible
This really depends on how long apart you need to run the function.
If it is => 10 minutes → I would go with Alarm Manager.
And then you receive these broadcasts via broadcast receiver. Note that this will need to be registered ether in your application manifest or via
context.registerReceiver(receiver,filter);
method For more information on Broadcast Receivers please refer to official Docs. Broadcast Receiver.If it is =< 10minutes → I would go with a Handler.