如何让Android服务每隔几秒钟播放一次意图?

时间:2013-04-17 02:25:35

标签: android service asynchronous

如果我已经创建了一项服务,我如何让它每隔X秒广播一次意图?我记得在一行中看到了一段代码

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

不幸的是,无论是循环还是循环,我都不确定类名或确切的方法名。只是一个名字会指出我正确的搜索方向。

2 个答案:

答案 0 :(得分:3)

您可以使用Handler.postDelayedHere 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);