我被困在这种情况下很久了…
我想使用Alarm Manager在特定时间显示通知,现在它在下列情况下工作:
当应用程序在后台运行时,无论设备是否锁定,都会在正确的时间显示通知。
当应用程序在后台被终止后,当设备未被锁定时,我仍然会收到正确的通知,但是当设备被锁定时,事情变得不对劲,我无法收到任何通知。
下面是代码alarmreceiver.java,所有需要的权限都已添加到androidmanifest.xml中:

@Override
public void onReceive(Context context, Intent intent) {
    WakeLocker.acquire(context);

    String action = intent.getAction();

    Log.d(TAG, action); //when app is killed and device is locked, no info is shown at the logcat

    if (ACTION_ALARM.equals(action)) {
        Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(2 * 1000);

        notify(context, "Jello!");
    }

    WakeLocker.release();
}

public static void alarm(Context context) {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.setAction(ACTION_ALARM);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 5 * 1000, pi);
    } else {
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 5 * 1000, pi);
    }
}

private void notify(Context context, String msg) {
    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
            new Intent(context, InfoActivity.class), 0);

    Notification notification =
            new NotificationCompat.Builder(context)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(context.getString(R.string.alarm))
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                    .setContentText(msg)
                    .setAutoCancel(true)
                    .setContentIntent(contentIntent).build();

    notificationManager.notify(1, notification);
}

添加的权限:
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE"/>

最佳答案

我刚刚找到了解决方案,设置了名为flag_include_stopped_packages的flag以达到报警的目的,一切都会好起来的。
以下是Android Developers中的插图

07-24 09:22