如何在启动完成时发送通知?

How to send notification on boot completed?

我有以下 class 称为 AlarmNotificationReceiver。 这个想法是在设备关闭时发送通知。似乎有什么不对劲,因为这没有发生。有什么想法吗?

public class AlarmNotificationReceiver extends BroadcastReceiver{
    public void onReceive(Context context, Intent intent) {

        if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){

             NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
            builder.setContentTitle("HEY I WAS INITIALIZED!");
            builder.setContentText("Good luck");
            builder.setSmallIcon(R.drawable.alert_icon);
            builder.setAutoCancel(true);
            builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
            builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.notif_red));

        //notification manager
            Notification notification = builder.build();
            NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
            manager.notify(1234, notification);
        }
    }
}

我还在清单中添加了以下几行:

    <receiver android:name=".AlarmNotificationReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
        </intent-filter>
    </receiver>

您没有创建通知渠道。您可以按如下方式创建通知:

public class AlarmNotificationReceiver extends BroadcastReceiver{
    public void onReceive(Context context, Intent intent) {

        if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){
            ...
            createNotificationChannel(context);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context,1000);
            ...
        }
     }
     private void createNotificationChannel(final Context context) {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            CharSequence name = "ChannelName";
            String description = "Channel description";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(1000, name, importance);
            channel.setDescription(description);
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
}