如果我已经创建了一项服务,我如何让它每隔X秒广播一次意图?我记得在一行中看到了一段代码
startThreadDelayed( new Thread() {
public void run() {
doStuff();
sendBroadcast(messageIntent);
startThreadDelayed(this, 1000);
}
}, 1000);
不幸的是,无论是循环还是循环,我都不确定类名或确切的方法名。只是一个名字会指出我正确的搜索方向。
答案 0 :(得分:3)
您可以使用Handler.postDelayed
。 Here is the documentation.
例如
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);
}
这里运行是一个标志,最好保持它作为volatile布尔值。因此,通过改变它的价值,你可以停止重复。
答案 1 :(得分:3)
您可以考虑使用AlarmManager。
通过使用它,您可以触发任何Intent
一次性或重复计划。
例如:
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);