2016-12-01 55 views
2

这里是我在应用程序类中的代码oncreate方法:但我看不到任何来自我的应用程序的消息。任何人都可以帮助我做到这一点?我该如何设置每5秒重复报警以显示消息

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

And on the broadcast receiver class I have the following code 

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

} 

}

回答

0

编辑答案

使用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); 
+0

@ Nick Friskel,谢谢你的回复。但我宣布了AlarmManger,但我没有包括它。我的问题是使用AlarmManager获取消息,每隔5秒在logcat中不使用服务类。我用Timer和处理器做了它,但我没有得到它的效率。 – Hiwot

+0

我已经编辑了答案:) –

+0

我按你说的做,但没有任何变化:(。 – Hiwot

0

如果你没有得到你所需要的确切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); 
} 

即报警方法将当前的广播接收器的工作,做一个实际的5秒延迟。