Search code examples
javaandroidbroadcastreceiverandroid-broadcastreceiver

How to send notification on boot completed?


I've got the following class called AlarmNotificationReceiver. The idea is to send a notification when the device is turned out. Something seems to be wrong since this isn't happening. Any ideas why?

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);
        }
    }
}

I also added the following lines to the manifest:

    <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>

Solution

  • You are missing creation of notification channel. You can create notification as follows:

    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);
            }
        }
    }