How to run a method every X seconds
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 runDate 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 secondhandler.postDelayed(new Runnable() { public void run() { System.out.println("myHandler: here!"); // Do your work here handler.postDelayed(this, delay); }}, delay);
You can please try this code to call the handler every 15 seconds via onResume() and stop it when the activity is not visible, via onPause().
Handler handler = new Handler();Runnable runnable;int delay = 15*1000; //Delay for 15 seconds. One second = 1000 milliseconds.@Overrideprotected void onResume() { //start handler as activity become visible handler.postDelayed( runnable = new Runnable() { public void run() { //do something handler.postDelayed(runnable, delay); } }, delay); super.onResume();}// If onPause() is not included the threads will double up when you // reload the activity @Overrideprotected void onPause() { handler.removeCallbacks(runnable); //stop handler when activity not visible super.onPause();}