android - 如果屏幕关闭,警报管理器将无法工作

标签 android alarmmanager

我的应用程序使用 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"/>

救命!

最佳答案

您的问题已得到解答here使用WakeLock对象。

有关 WaveLock 的更多信息,请参阅 Android Developers :

A wake lock is a mechanism to indicate that your application needs to have the device stay on.

关于android - 如果屏幕关闭,警报管理器将无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42238037/

相关文章:

android - 如何在Android中设置可靠的长期闹钟?

android - AlarmManager 无法在装有 Android 的华硕 ZenFone 2 设备上运行

java - firebase mp3播放器中的暂停功能

Android Eclipse,两个不同选项卡中的两个 Activity ,不断调用 onCreate()!

Android:在 WebView 中加载的图像像素质量降低

Android:使用 AlarmManager 设置定期警报

android - 如何在没有 AlarmManager 的情况下使用 Android 的传感器批处理

android - AlarmManager、TimePicker 和 Wifi 控制。如何?

android - 如何导入刚刚在eclipse中删除的项目

android - Eclipse 在调试 ctrl+shift+i 时丢失了检查快捷方式