How to run a method every X seconds

VansFannel picture VansFannel · Jul 11, 2012 · Viewed 172.2k times · Source

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?

Answer

Jug6ernaut picture Jug6ernaut · Jul 11, 2012

The solution you will use really depends on how long you need to wait between each execution of your function.

If you are waiting for longer than 10 minutes, I would suggest using AlarmManager.

// Some time when you want to run
Date when = new Date(System.currentTimeMillis());

try {
    Intent someIntent = new Intent(someContext, MyReceiver.class); // intent to be launched

    // Note: this could be getActivity if you want to launch an activity
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
        context,
        0, // id (optional)
        someIntent, // intent to launch
        PendingIntent.FLAG_CANCEL_CURRENT // PendingIntent flag
    );

    AlarmManager alarms = (AlarmManager) context.getSystemService(
        Context.ALARM_SERVICE
    );

    alarms.setRepeating(
        AlarmManager.RTC_WAKEUP,
        when.getTime(),
        AlarmManager.INTERVAL_FIFTEEN_MINUTES,
        pendingIntent
    );
} catch(Exception e) {
    e.printStackTrace();
}

Once you have broadcasted the above Intent, you can receive your Intent by implementing a BroadcastReceiver. Note that this will need to be registered either in your application manifest or via the context.registerReceiver(receiver, intentFilter); method. For more information on BroadcastReceiver's please refer to the official documentation..

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent)
    {
        System.out.println("MyReceiver: here!") // Do your work here
    }
}

If you are waiting for shorter than 10 minutes then I would suggest using a Handler.

final Handler handler = new Handler();
final int delay = 1000; // 1000 milliseconds == 1 second

handler.postDelayed(new Runnable() {
    public void run() {
        System.out.println("myHandler: here!"); // Do your work here
        handler.postDelayed(this, delay);
    }
}, delay);