Android Notification Not Appearing As Heads Up

2.5k Views Asked by At

I am using the following to present notifications to users on Android which currently works fine but I am having an issue that the notification appears in the status bar but does not come up as a heads up like a Facebook or WhatsApp notification does on the device? I get the notification but have to pull down on the status bar to view it. I am wondering is there a way to make this appear on the top of the screen in bubble format or is this something that varies between phone settings?

Code is attached below:

MainActivity

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addNotification(10,"eventname","roomname");
        addNotification(25,"eventname2","roomname2");
    }
    public void addNotification(int test, String test2, String test3){
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, AlarmReceiver.class);
        intent.putExtra("test",test2);
        intent.putExtra("test2",test3);
        final int _id = 50;
        Random random = new Random();
        final int randomInt = random.nextInt();
        System.out.println("random integer:" + randomInt);
        PendingIntent appIntent = PendingIntent.getBroadcast(this, randomInt, intent,PendingIntent.FLAG_UPDATE_CURRENT);

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, test);
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), appIntent);
    }
}

AlarmReceiver

public class AlarmReceiver extends BroadcastReceiver{
    private static final String CHANNEL_ID = "com.singhajit.notificationDemo.channelId";

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent notificationIntent = new Intent(context, NotificationActivity.class);
        String passed = intent.getStringExtra("test");
        String passed2 = intent.getStringExtra("test2");
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(NotificationActivity.class);
        stackBuilder.addNextIntent(notificationIntent);
String messageBody = "Your event " + passed + " is about to start in 15 minutes, in room "+passed2;
        PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification.Builder builder = new Notification.Builder(context);

        builder.setStyle(new Notification.BigTextStyle(builder)
                .bigText(messageBody)
                .setBigContentTitle("UA Reloaded Event Starting")
                .setSummaryText("Tap To View Info"))
                .setContentText(messageBody)
                .setSmallIcon(R.drawable.ic_launcher)
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                .setPriority(Notification.PRIORITY_MAX);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(CHANNEL_ID);
        }

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            String name = "NotificationDemo";
            String description = "NotificationDemo";
            int importance = NotificationManager.IMPORTANCE_HIGH; //Important for heads-up notification
            NotificationChannel channel = new NotificationChannel("1", name, importance);
            channel.setDescription(description);
            channel.setShowBadge(true);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
           // NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0, builder.build());
    }
}
4

There are 4 best solutions below

0
On

You updated your channel importance, which is not possible as stated in the documentation (https://developer.android.com/training/notify-user/channels#CreateChannel).

So your problem should be resolved by changing the channelId to something other than "1", as the ids for Channels must be unique.

0
On

Here is my kotlin class all you need is to call notificate(title: String, text: String) method, if you want it in java you can convert it

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationManager
import android.content.Context
import android.support.v4.app.NotificationCompat
import beacon.geisoft.org.beacontrakerkotlin_rebuild.R
import android.os.Build
import android.support.annotation.RequiresApi
import android.support.v4.content.ContextCompat.getSystemService
import android.app.NotificationChannel
import android.app.PendingIntent
import android.content.Intent
import android.graphics.Color
import android.media.RingtoneManager
import android.support.v4.content.ContextCompat.getSystemService
import android.support.v4.app.NotificationManagerCompat
import beacon.geisoft.org.beacontrakerkotlin_rebuild.activities.MainActivity
import android.preference.PreferenceManager
import android.content.SharedPreferences




class Notifications (var context: Context){

/**
 * Send notification to the client device
 * @param text String
 */
@SuppressLint("PrivateResource")
private fun notificate(title: String, text: String, id: Int, notificationManager: NotificationManager) {

    val intent1 = Intent(context, MainActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(context, 123, intent1, PendingIntent.FLAG_UPDATE_CURRENT)
    val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && notificationManager.getNotificationChannel("beacon.geisoft.org.beacontraker_rebuild") == null) {

        val chan2 = NotificationChannel("beacon.geisoft.org.beacontraker_rebuild", "Pazienti", NotificationManager.IMPORTANCE_HIGH)
        chan2.lightColor = Color.BLUE
        chan2.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
        notificationManager.createNotificationChannel(chan2)

        /*
        notificationManager.createNotificationChannel(NotificationChannel("beacon.geisoft.org.beacontraker_rebuild",
                "Pazienti", NotificationManager.IMPORTANCE_HIGH))*/
    }
    val builder = NotificationCompat.Builder(context, "beacon.geisoft.org.beacontraker_rebuild")
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        builder.setContentTitle(title)  // required
                .setContentText(text)  // required
                .setDefaults(Notification.DEFAULT_ALL)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.beaconicon32) // required
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.beaconicon64))
                .setSound(defaultSoundUri)
    }else {
        builder.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setContentTitle(title)
                .setContentText(text)
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.beaconicon32) // required
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.beaconicon64))
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setSound(defaultSoundUri)
    }
    notificationManager.notify(id, builder.build());
}

fun notificate(title: String, text: String, id: Int){
    val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
    notificate(title, text, id, notificationManager!!)
}

fun notificate(title: String, text: String){
    val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
    var num: Int
    do {
        num = (Math.random() * 100).toInt()
    } while (notificationExist(notificationManager!!, num))
    notificate(title, text, num, notificationManager)
}

fun notificationExist(notificationManager: NotificationManager, id: Int): Boolean {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val notifications =
                notificationManager.activeNotifications
        for (notification in notifications) {
            if (notification.getId() == id) {
                return true
            }
        }
    }
    return false
}
}
0
On

If you still need an answer or for anyone else in order to show the notification as heads-up you have to add your channel id to the Builder. .setChannelId(CHANNEL_ID)

like so:

  val notification = NotificationCompat.Builder(getContext(), CHANNEL_ID)
            .setSmallIcon(...)
            .setContentTitle(getContext().getString(R.string.app_name))
            ...
            .setChannelId(CHANNEL_ID)
            ...
            .build()

And don't forget about the NotificationChannel importance and notification priority (set them to high/max if needed)

1
On

Well the solution is simple when we use NotificationChannel and set the IMPORTANCE to high then we have to uninstall the app then install it again otherwise it will not work.