预定的闹钟从不呼叫接收器 class

Scheduled alarm never calls receiver class

我正在尝试将闹钟设置为每 5 分钟触发一次。

这是设置闹钟的代码:

   @Override
public void scheduleAlarmManager() {
    Timber.i("After SignIn sets AlarmManager");
    // broadcast
    Intent intent = new Intent(this, PatientAlarmReceiver.class);
    intent.setAction(PATIENT_START_ALARM_ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
            this, REQUEST_CODE, intent, 0);

    // and set alarmManager
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

    Calendar currentCal = Calendar.getInstance();
    long currentTIme = currentCal.getTimeInMillis();

    // if there's not an Alarm already set then set one
    if (!isAlarmSet(this)) {
        Timber.i("Alarm not set - so set one");
        alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                currentTIme + TWO_MINS_DURATION, TWO_MINS_DURATION, pendingIntent);
    }

}

并且我可以验证我是否正确设置了警报,因为我在 logcat 中看到了我使用 Timber 记录的消息。

我的接收器 class 是:

public class PatientAlarmReceiver extends BroadcastReceiver {

public static final String TAG = "PATIENT-ALARM-RECEIVER";
public static final String PATIENT_START_ALARM_ACTION = "bp.headsup.receivers.alarm.patient";

@Override
public void onReceive(Context context, Intent intent) {
    Log.i(TAG, "Inside OnReceive Patient");
    Timber.i("Inside OnReceive Patient");

    if (intent == null || intent.getAction() == null) {
        return;
    }

    String action = intent.getAction();
    if (PATIENT_START_ALARM_ACTION.equalsIgnoreCase(action)) {
        onStartCheckForConnectionRequest(context);
    }
}

/**
 * If is connected to network starts services
 */
private void onStartCheckForConnectionRequest(Context context) {
    NetworkUtils networkUtils = new NetworkUtils(context);
    if (networkUtils.isNetworkConnected()) {
        Intent checkForConnRequestIntent = new Intent(context, PatientCheckForConnectionRequestService.class);
        context.startService(checkForConnRequestIntent);
        Timber.i("Starts Service From PatientALARMMANAGER");
    }
}

}

而且我已经在清单中声明了:

        <!-- Receivers -->
    <receiver
        android:name="bp.headsup.receivers.PatientAlarmReceiver" />

另外如果我 运行 : adb shell dumpsys alarm 我可以看到:

  ELAPSED_WAKEUP #0: Alarm{42d804e8 type 2 bp.headsup.mock}
operation=PendingIntent{42d0c230: PendingIntentRecord{42d0f000 bp.headsup.mock broadcastIntent}}

上面回复中的模拟是我正在使用的 sourceSet - 不知道它是否与此有关我只是提到它。

问题是我从未在 logcat 中读过我的接收器 class 中 onReceive 中的消息,显然没有服务启动。任何人都可以帮忙吗?我使用的设备 运行s 与 kitKat 4.4 (api 19) 但我也用模拟器尝试过,结果是一样的。

您正在设置一个 ELAPSED_REALTIME 警报,该警报基于自上次启动以来的时间。但是,您根据 "wall clock" 向它传递了一个开始时间,因此您的闹钟实际上设置在很远的将来。

您可以将闹钟更改为 RTC 类型,或者从 SystemClock.elapsedRealtime() 获取开始时间。鉴于您描述的行为,保留经过的类型并更正开始时间似乎是合适的。