我试图设置一个警报,将一个意图发送给广播接收器。接收器应该在logcat中打印一行,说明它已经工作。但是我没有得到接收器正在接收任何东西的迹象。我已经检查了所有我能想到的东西。因为我不知所措,有人可以给我一些指导吗?
警报方法
public void scheduleNextUpdate()
{
Intent intent = new Intent(MainActivity.this,AlarmReceiver.class);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
long currentTimeMillis = System.currentTimeMillis();
long nextUpdateTimeMillis = currentTimeMillis * DateUtils.MINUTE_IN_MILLIS;
Time nextUpdateTime = new Time();
nextUpdateTime.set(nextUpdateTimeMillis);
if (nextUpdateTime.hour < 8 || nextUpdateTime.hour >= 22)
{
nextUpdateTime.hour = 8;
nextUpdateTime.minute = 0;
nextUpdateTime.second = 0;
nextUpdateTimeMillis = nextUpdateTime.toMillis(false) + DateUtils.DAY_IN_MILLIS;
}
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, nextUpdateTimeMillis, pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, nextUpdateTimeMillis,nextUpdateTimeMillis,pendingIntent);
boolean alarmUp = (PendingIntent.getBroadcast(this, 0,
new Intent(MainActivity.this,AlarmReceiver.class),
PendingIntent.FLAG_NO_CREATE) != null);
if (alarmUp)
{
Log.d("myTag", "Alarm is already active");
}
}
ReceiverClass
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("Alarm Received");
intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
System.out.println("Alarm Received");
}
清单
<receiver android:name=".AlarmReceiver"></receiver>
答案 0 :(得分:4)
这个数学似乎错了。我相信你正试图设置一个几代人不会发出的警报:
long currentTimeMillis = System.currentTimeMillis();
long nextUpdateTimeMillis = currentTimeMillis * DateUtils.MINUTE_IN_MILLIS;
也许你打算在一分钟内报警:
long nextUpdateTimeMillis = currentTimeMillis + DateUtils.MINUTE_IN_MILLIS;
无论如何首先使用:
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 10000,
5000,
pendingIntent);
要确认您的设置是否正确,如果是,则需要重新计算nextUpdateTimeMillis
。