首页 > 解决方案 > Android 警报管理器未触发,尝试发送通知

问题描述

我正在尝试设置一个一次性警报来唤醒我的应用程序,然后向用户发送通知。

我将在未来设置 1 分钟的闹钟,但我的广播接收器从未被调用过。

这就是我安排AlarmManager和构建的方式Notification

private void scheduleNotification(Date notificationdate) {
    Log.d("PSBMF", "scheduling notification at "+notificationdate);

    Intent intent = new Intent(Intent.ACTION_DIAL);
    intent.setData(Uri.parse("tel:"+AppController.statewidephone));
    PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 0, intent, 0);

    String notificationmessage = "Test Message";
    String channelid = "Channel Id";
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getActivity(), channelid)
            .setSmallIcon(R.drawable.ic_warning_black_36dp)
            .setContentTitle("Notification Title")
            .setContentText("Notification Content")
            .setStyle(new NotificationCompat.BigTextStyle().bigText("Notification Content"))
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setContentIntent(pendingIntent)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setDefaults(Notification.DEFAULT_ALL)
            ;

    Notification notification = mBuilder.build();

    Intent notificationIntent = new Intent(mActivity, NotificationPublisher.class);
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, 1);
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
    PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(mActivity, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    long notificationTimeInMillis = notificationdate.getTime();
    AlarmManager alarmManager = (AlarmManager)mActivity.getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, notificationTimeInMillis, pendingAlarmIntent);

}

我的NotificationPublisher.class样子是这样的:

public class NotificationPublisher extends BroadcastReceiver {

    public static String NOTIFICATION_ID = "notification-id";
    public static String NOTIFICATION = "notification";

    public void onReceive(Context context, Intent intent) {

        Log.d("NP", "NOTIFICATION RECEIVED: "+context);

        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

        Notification notification = intent.getParcelableExtra(NOTIFICATION);
        int id = intent.getIntExtra(NOTIFICATION_ID, 0);
        notificationManager.notify(id, notification);

    }
}

我已经NotificationPublisher/BroadcastReceiver通过将其放入<application/>清单的标签中来注册我的:

<receiver android:name=".NotificationPublisher"/>

我还缺少什么?为什么我的警报不会被触发并调用该onReceive方法?

标签: androidalarmmanagerandroid-notifications

解决方案


感觉链接这与广播接收器的更改有关。

在清单中注册接收器将不再适用于:

注意:如果您的应用程序以 API 级别 26 或更高级别为目标,则您不能使用清单来声明隐式广播(不专门针对您的应用程序的广播)的接收器,但一些不受该限制的隐式广播除外。在大多数情况下,您可以改用计划作业。

上面的注释是从链接中复制的。

希望这可以帮助。


推荐阅读