0

我试图设置一个将向广播接收器发送意图的警报。然后接收者应该在 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");
        }
}

接收者等级

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>
4

1 回答 1

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.

于 2012-11-27T22:00:47.907 回答