Heads-up Notification - Android Lollipop

user1719863 picture user1719863 · Oct 19, 2014 · Viewed 51.5k times · Source

I'm trying to show a notification-type heads-up but I could not. What I tried

final Notification.Builder notif = new Builder(getApplicationContext())
    .setContentTitle(getString(R.string.title))
    .setContentText(getString(R.string.text))
//  .setTicker(getString(R.string.tick)) removed, seems to not show at all
//  .setWhen(System.currentTimeMillis()) removed, match default
//  .setContentIntent(contentIntent) removed, I don't neet it
    .setColor(Color.parseColor(getString(R.color.yellow))) //ok
    .setSmallIcon(R.drawable.ic_small) //ok
    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
//  .setCategory(Notification.CATEGORY_CALL) does not seem to make a difference
    .setPriority(Notification.PRIORITY_MAX); //does not seem to make a difference
//  .setVisibility(Notification.VISIBILITY_PRIVATE); //does not seem to make a difference

mNotificationManager.notify(Constants.NOTIFICATION_ID, notif.build());

The notification is shown only as an icon in the bar. I'm using API 21 on API 21 emulator (not L preview) I have tried:
android:Theme.Holo.NoActionBar,
android:Theme.Holo.NoActionBar.Fullscreen
and NotificationCompat.Builder

SDK examples are not available. does anyone know how to do it?

I made it working by adding:

.setDefaults(Notification.DEFAULT_VIBRATE)

is this the best way?

Answer

Mygod picture Mygod · Dec 21, 2014

According to Notifications, you are required to set a vibrate or ringtone to make Heads-up work. However, here's a quick hack that doesn't require VIBRATE permission to produce a head-up notification:

notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
if (Build.VERSION.SDK_INT >= 21) notificationBuilder.setVibrate(new long[0]);

EDIT:

Don't abuse heads-up notification. See here for when to use heads-up notification:

MAX: For critical and urgent notifications that alert the user to a condition that is time-critical or needs to be resolved before they can continue with a particular task.

HIGH: Primarily for important communication, such as messages or chat events with content that is particularly interesting for the user. High-priority notifications trigger the heads-up notification display.