Search code examples
javaandroidandroid-studioalarmmanagerandroid-notifications

Android: Notification that requires user interaction / input


I'm programming some Android App that must make some Notification/Alarm after event occurs. Im wondering is there any function for NotificationManager like requireInteraction()?

Now when the certain event occurs the app just shows one notification for 1 sec, that's it..i'd like user to click OK to stop this vibration/sound

I found some code for notification from here: NotificationCompat.Builder deprecated in Android O

Thanks @Mehul

public void showNotification (String from, String notification, 
 Intent intent) {

        int requestID = (int) System.currentTimeMillis();

        PendingIntent pendingIntent = PendingIntent.getActivity(
                context,
                requestID,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT
        );


        String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);

            // Configure the notification channel.
            notificationChannel.setDescription("Channel description");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            notificationChannel.enableVibration(true);
            notificationManager.createNotificationChannel(notificationChannel);
        }


        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
        Notification mNotification = builder
                .setContentTitle(from)
                .setContentText(notification)




                .setContentIntent(pendingIntent)

                .setAutoCancel(true)

                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
                .build();

        notificationManager.notify(/*notification id*/requestID, mNotification);

    }

This one shows notification and it doesnt wait for user Input


Solution

  • If there is a need to add the buttons or action after clicking on notification you can use in your builder:

    To add an button:

    .addAction(new NotificationCompat.Action(*icon*, "Title", *intent for notification*));
    

    or to add action that happen after user click the notification

    .setContentIntent(*intent*);
    

    Check the documentation about tab action and actions if you need more details.