How to get Android service for broadcasting intentions every few seconds?

If I created a service, how do I get it to broadcast an intention every X seconds? I remember how a piece of code was shown along the lines

startThreadDelayed( new Thread() { public void run() { doStuff(); sendBroadcast(messageIntent); startThreadDelayed(this, 1000); } }, 1000); 

Unfortunately, I’m not sure of either the class name or the exact method name, whatever the loop. Just the name will point me in the right direction of the search.

+2
source share
2 answers

you can use Handler.postDelayed . Here is the documentation.

Example

 Handler h = new Handler(); YourClass yourRunnable = new YourClass(); h.postDelayed(youRunnable,1000); public class YourClass implements Runnable{ public void run(){ doStuff(); sendBroadcast(messageIntent); if(running) h.postDelayed(youRunnable,1000); } 

here the flag works better to keep it as a volatile boolean. To change the value, you can stop repeating.

+2
source

You can use AlarmManager . Using it, you can run any Intent one-time or repeated with any schedule.

For instance:

 Intent i = new Intent(this, YourReceiver.class); PendingIntent broadcast = PendingIntent.getBroadcast(this, 0, i, 0); long first = System.currentTimeInMillis(); // now long interval = 5 * 1000; // every 5 seconds AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); am.setRepeating(AlarmManager.RTC, first, interval, broadcast); 
+3
source

All Articles