4

I have Implemented heads up notification for my app. Code is like this:

private  String CHANNEL_ID = "message_notifications";
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID,"message_notifications", NotificationManager.IMPORTANCE_HIGH);


@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);


    String notification_title = remoteMessage.getNotification().getTitle();
    String notification_message = remoteMessage.getNotification().getBody();

    String click_action = remoteMessage.getNotification().getClickAction();


    String user_id = remoteMessage.getData().get("user_id");
    String user_name = remoteMessage.getData().get("user_name");
    String GROUP_KEY_CHIT_CHAT = "com.android.example.Chit_Chat";


    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setSmallIcon(R.drawable.chitchat_icon)
                    .setContentTitle(notification_title)
                    .setAutoCancel(true)
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setGroup(GROUP_KEY_CHIT_CHAT)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
                    .setContentText(notification_message);


    if (Build.VERSION.SDK_INT >= 21) mBuilder.setVibrate(new long[0]);
    Intent resultIntent = new Intent(click_action);
    resultIntent.putExtra("user_id", user_id);
    resultIntent.putExtra("user_name",user_name);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addNextIntentWithParentStack(resultIntent);
    stackBuilder.addParentStack(MainActivity.class);

    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(
                    0,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );

    mBuilder.setContentIntent(resultPendingIntent);


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

    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        mChannel.setShowBadge(true);
        mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        mNotificationManager.createNotificationChannel(mChannel);
        mBuilder.setChannelId(CHANNEL_ID);
    }

    mNotificationManager.notify(mNotificationId,mBuilder.build());
}

Problem is It only works correctly when I do the settings for the notification as popup and sound else it appears like simple notification. Whatsapp and other applications are by default settuped to use them. I want to do the same. I want to programmatically set the settings for my app to use heads up notification by default without going into the setting to enable it. Can anybody help me how to do that? enter image description here

I need to set it to sound and popup it doesn't set by default

Rehan
  • 454
  • 7
  • 19
  • https://stackoverflow.com/questions/33510861/how-to-show-heads-up-notifications-android – Kiran Oct 29 '19 at 11:04
  • Possible duplicate of [How to show Heads up notifications android](https://stackoverflow.com/questions/33510861/how-to-show-heads-up-notifications-android) – Edric Oct 29 '19 at 11:05
  • I have done all of these solution if you see my code. It is working but I need to do some settings in my phone onlye then it works – Rehan Oct 29 '19 at 11:07
  • The above solutions are all implemented in above code. Please read the question before marking it as duplicate – Rehan Oct 29 '19 at 11:12

1 Answers1

4

Set the importance level of notification channel to IMPORTANCE_HIGH to appears as a heads-up notification.

Set notification as ongoing using setOngoing method if you want the notification dismissed only while performing an action. Ongoing notifications cannot be dismissed by the user, so your application or service must take care of canceling them.

If you want to show the notification in Do Not Disturb mode as well you can set category to CATEGORY_ALARM

If you want an intent to launch instead of posting the notification to the status bar for demanding the user's immediate attention use setFullScreenIntent

Sample code block

        Intent launch = new Intent(context, TargetActivity.class);
        launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0,
                launch, PendingIntent.FLAG_UPDATE_CURRENT);
        createNotificationChannel(mContext, NOTIFICATION_CHANNEL_ID, NotificationManager.IMPORTANCE_HIGH,
                R.string.notification_channel_name, R.string.notification_channel_description);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID);
        builder.setContentTitle("Title");
        builder.setContentText("Content Text");
        builder.setStyle(new NotificationCompat.BigTextStyle()
                .bigText("Big Content Text"));
        builder.setSmallIcon(R.drawable.status_icon);
        builder.setFullScreenIntent(pendingIntent, true);
        builder.setOngoing(true);
        builder.setAutoCancel(true);
        builder.setCategory(NotificationCompat.CATEGORY_ALARM);
        builder.addAction(0, "Action Text", pendingIntent);
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mContext);
        notificationManager.notify(COMPLETE_NOTIFICATION_ID, builder.build());

   /**
     * create Notification channel
     * @param context
     * @param channelId
     * @param channelName
     * @param channelDescription
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void createNotificationChannel(Context context, String channelId, int importance, int channelName, int channelDescription) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = context.getString(channelName);
            String description = context.getString(channelDescription);
            NotificationChannel channel = new NotificationChannel(channelId, name, importance);
            channel.setDescription(description);
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }

    }
Anoop M Maddasseri
  • 10,213
  • 3
  • 52
  • 73
  • Can you be precise. I just want heads up notification. I have also set the importance to high but it only pops if I long press notification and change its mode to sound and popup. Can I set that mode by defualt for my app? – Rehan Oct 29 '19 at 11:48
  • 1
    Please check creating the channel first as I posted (See order of the code). Then do a fresh installation (Uninstall then Re-Install) of the app to recreate the channel. – Anoop M Maddasseri Oct 29 '19 at 12:07
  • Please update your query with the device environment if it doesn't work. I think Samsung one UI custom ROM disabled heads up notification by default, you need to enable them in notification settings as u has shown in the attached screenshot. Try with a device that runs in stock android/android one. – Anoop M Maddasseri Oct 29 '19 at 12:32
  • My Questions is if SamsungUI doesn't allow heads up than how do other apps are implementing them? – Rehan Oct 29 '19 at 12:49
  • I have uploaded my complete code. Please guide me accordingly if there is any mistake in the sequence. – Rehan Oct 29 '19 at 12:57
  • Try with the code sample I posted, there you can see the notification channel has been created after the `PendingIntent` – Anoop M Maddasseri Oct 29 '19 at 14:00
  • @Anil Sorry ! But code didn't helped me. Results are same. – Rehan Oct 29 '19 at 15:42
  • @rehan were you able to find any solution? – Rahul Feb 11 '20 at 05:20
  • @Rahul no I couldn't – Rehan Feb 11 '20 at 06:08
  • Your channel needs to explicitly setSound(uri) and setVibrate(pattern), that's why heads up is not working properly. Pre-Oreo, we could modify these variables within the Notification.Builder object, but we must now do this within the Notification Channel. – zuko May 19 '20 at 03:41