我希望我的本机无头JS在后台运行,每30秒执行一次作业。当符合条件时,我想在Android手机上收到通知提醒。手机打do睡之前,一切正常。警报作业设法按时触发通知消息,就像我在警报管理器中配置的一样。
直到手机打ze睡之后,它才设法在只有手机醒来的屏幕上显示通知。它确实有效,但并非我所期望的。屏幕唤醒仅大约每4-5分钟发生一次,而不是每30秒发生一次。我什至尝试添加另一个警报作业(2个警报计划作业),但仍然无法实现。我的目的是让我的手机至少在触发onReceive()时显示暗淡显示。我错过了什么?还是我该怎么办?
public class AlarmHelper {
private static final int PI_SELF_SCHEDULED_ALARM = 1000;
private static final int PI_REPEATING_ALARM = 1001;
private final Context context;
private AlarmManager alarmManager;
public AlarmHelper(Context context) {
this.context = context;
alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
}
public void setNextSelfSchedulingAlarm() {
final long fourtySecondsFromNow = System.currentTimeMillis() + SECONDS.toMillis(30);
Intent exactIntent = new Intent(context, AlarmBroadcastReceiver.class).setAction(SELF_SCHEDULING_ALARM);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, PI_SELF_SCHEDULED_ALARM, exactIntent, FLAG_UPDATE_CURRENT);
if (SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(RTC_WAKEUP, fourtySecondsFromNow, pendingIntent);
} else if (SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(RTC_WAKEUP, fourtySecondsFromNow, pendingIntent);
} else {
alarmManager.set(RTC_WAKEUP, fourtySecondsFromNow, pendingIntent);
}
}
public void startRepeatingAlarm() {
final int repeatingIntervalInSeconds = 30;
final long tenSecondsFromNow = System.currentTimeMillis() + SECONDS.toMillis(30);
Intent repeatingIntent = new Intent(context, AlarmBroadcastReceiver.class).setAction(REPEATING_ALARM);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, PI_REPEATING_ALARM, repeatingIntent, FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(RTC_WAKEUP, tenSecondsFromNow, SECONDS.toMillis(repeatingIntervalInSeconds), pendingIntent);
}
}
&
public class AlarmBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "AlarmReceiver";
@Override
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock screenWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "ScreenLock tag from AlarmListener");
try {
screenWakeLock.acquire();
Hawk.init(context).build();
String action = intent.getAction();
if (action == null) {
screenWakeLock.release();
return;
}
if (REPEATING_ALARM.equals(action)) {
} else if (SELF_SCHEDULING_ALARM.equals(action)) {
AlarmHelper alarmHelper = new AlarmHelper(context);
alarmHelper.setNextSelfSchedulingAlarm();
}
Intent intentService = new Intent(context, HeadlessTaskService.class);
context.startService(intentService);
} finally {
screenWakeLock.release();
}
}
}