2

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());
    }
}
Curtis Boylan
  • 827
  • 1
  • 7
  • 23
  • Why should it even be shown as a bubble? You are just creating a normal notification for android. the bubbles are just app specifics – finki Nov 08 '18 at 10:50
  • I would like it to appear on the top and be able to read what the application notifies without having to pull down on the status bar, right now the notification makes the phone buzz and appears the app logo in the status bar but does not show my notification until i pull down on the status bar @finki – Curtis Boylan Nov 08 '18 at 10:52
  • Yea. That's exactly what your code is supposed to do. Seems like you are new to android, check this video about the feature you are requesting: https://www.youtube.com/watch?v=LoO0nLpFfWU – finki Nov 08 '18 at 10:57
  • @finki I think you're misunderstanding. I don't want like facebook bubbles. I want it to be a heads up notification such as on here: https://developer.android.com/guide/topics/ui/notifiers/notifications – Curtis Boylan Nov 08 '18 at 11:06
  • Then update your question and exchange bubbles with heads up! I would try setting the importance of the notification to high/urgent. just as the documentation specifies it: https://developer.android.com/guide/topics/ui/notifiers/notifications#importance – finki Nov 08 '18 at 11:08
  • @finki I have already updated it with my new code, which is also not working. I am using importance etc, maybe you'd know? – Curtis Boylan Nov 08 '18 at 11:17
  • I had the same problem, now i'll search for my project to help you – Alesandro Giordano Nov 08 '18 at 13:46
  • Why do you need **PRIORITY_MAX**? – IgorGanapolsky May 03 '20 at 21:40

3 Answers3

1

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.

finki
  • 2,063
  • 1
  • 20
  • 23
1

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)

Dharman
  • 30,962
  • 25
  • 85
  • 135
Top4o
  • 547
  • 6
  • 19
-1

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