Tuesday, April 16, 2013

[android help] How do I get an Android service to broadcast an intent every few seconds?

How do I get an Android service to broadcast an intent every few seconds? - Stack Overflow








Tell me more ×

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

















If I've created a service, how do I get it to broadcast an intent every X seconds? I remember seeing a snippet of code along the lines



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


Unfortunatelly I'm not sure of either the class name, or the exact method name, for whatever is looping. Just a name would point me in the right direction of searching.


























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


For 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 running is a flag better keep it as volatile boolean. So that by changing it's value you can stop the repeatition.


























You may consider using AlarmManager. By using it you can trigger any Intent one-time or recurring with any schedule.


For example:



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);



















default







.

stackoverflow.comm

No comments:

Post a Comment

Google Voice on T-Mobile? [General]

Google Voice on T-Mobile? So I recently switched from a GNex on Verizon to a Moto X DE on T-Mobile. I had always used Google Voice for my v...