我的应用程序使用AlarmManager。 我尝试下一个代码来创建报警
public void startAlarm(int timeInterval){
if (timeInterval == -1)
return;
int id = generateIdAlarmManager();
AlarmManager manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = getPendingIntent(id, timeInterval * 60000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
final AlarmManager.AlarmClockInfo alarmClockInfo = new AlarmManager.AlarmClockInfo(System.currentTimeMillis() + timeInterval * 60000, pendingIntent);
manager.setAlarmClock(alarmClockInfo, pendingIntent);
}
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
manager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeInterval * 60000, pendingIntent);
else
manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeInterval * 60000, pendingIntent);
SharedPreferences.Editor edit = preferences.edit();
edit.putInt(ALARM_MANAGER_ID_ALARM_CHECK_SMS, id);
edit.putInt(ALARM_MANAGER_INTERVAL_CHECK_SMS, timeInterval);
edit.putBoolean(ALARM_MANAGER_ENABLE_CHECK_SMS, true);
edit.apply();
edit.commit();
}
如果屏幕打开,则AlarmManager正常工作。如果屏幕关闭AlarmManager不工作。 我添加
<uses-permission android:name="android.permission.WAKE_LOCK"/>
帮助!
答案 0 :(得分:1)
致电
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),timeIntervalForBroadcast, pendingIntent)
而不是alaramManager的manager.set()方法。
答案 1 :(得分:0)