Android服务在1分钟后再次呼叫自己

时间:2012-08-26 18:56:22

标签: android service alarmmanager

我正在尝试制作一个服务,醒来并在一分钟后再次呼叫自己(在这个例子中,我知道它对电池不利)。

以下是代码的一部分:

public class SpeechService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();

        setUpNextAlarm();
    }

    public void setUpNextAlarm(){
        Intent intent = new Intent(SpeechService.this, this.getClass());
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);

        long currentTimeMillis = System.currentTimeMillis();
        long nextUpdateTimeMillis = currentTimeMillis + 1 * DateUtils.MINUTE_IN_MILLIS;

        // Schedule the alarm!
        AlarmManager am = (AlarmManager)ContextManager.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP,nextUpdateTimeMillis, pendingIntent);
        Log.e("test","I am back!");
    }

    protected void onHandleIntent(Intent intent)
    {
        Log.e("test","I am back!");
        setUpNextAlarm();
    }
}

正如你所看到我在服务创建时调用setUpNextAlarm,我在最后看到了日志,但随后再也没有调用该服务。我在IndentService中尝试了这个,它可以工作,但我需要它在正常的服务中工作:(。

谢谢

2 个答案:

答案 0 :(得分:1)

使用

 PendingIntent.getService

 PendingIntent.getBroadcast

您正在获得广播意图。

答案 1 :(得分:0)

我最终使用了Service和IntentService。 IntentService正在使用AlarmManager,然后它正在调用服务。