这是我在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();
}
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 :(得分:1)
如果您没有得到所需的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秒延迟。
答案 1 :(得分: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);