如何设置每 5 秒重复一次闹钟以显示消息

how can I set repeating alarm every 5 second to show message

这是我在应用程序 class 中 oncreate 方法中的代码:但是我看不到来自我的应用程序的任何消息。谁能帮我做这个?

Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
public void startAlarm() {
    manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    int interval = 5000;

    manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
    Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
}

在广播接收器上class我有以下代码

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        // For our recurring task, we'll just display a message
        Toast.makeText(arg0, "I'm running", Toast.LENGTH_SHORT).show();
    }
}

已编辑答案

使用 setInexactRepeating() 而不是 setRepeating()setRepeating只需要设定的间隔,最短的是INTERVAL_FIFTEEN_MINUTES。 setInexactRepeating() 是将重复间隔设置为 1000 毫秒或 5000 毫秒的唯一方法。

变化:

 manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);

 manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);

如果您没有获得所需的确切 5 秒延迟,则需要使用处理程序。任何类型的延迟 5 秒的警报都将无法正常工作,因为从 Android 5.x 开始,基本上所有重复的警报都无法节省电池寿命。

我已修改您的代码以使用处理程序:

startAlarm();

public void startAlarm() {
    final Handler h = new Handler();
    final int delay = 5000; //milliseconds

    h.postDelayed(new Runnable(){
        public void run(){
            //do something

            Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
            sendBroadcast(alarmIntent);

            h.postDelayed(this, delay);
        }
    }, delay);
}

该警报方法将与您当前的 BroadcastReceiver 一起使用,并实际延迟 5 秒。