147

I need a program that will add a notification on Android. And when someone clicks on the notification, it should lead them to my second activity.

I have established code. The notification should be working, but for some reason it is not working. The Notification isn't showing at all. I don't know what am I missing.

Code of those files:

Notification n = new Notification.Builder(this)
        .setContentTitle("New mail from " + "test@gmail.com")
        .setContentText("Subject")
        .setContentIntent(pIntent).setAutoCancel(true)
        .setStyle(new Notification.BigTextStyle().bigText(longText))
        .build();

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Hide the notification after it's selected

notificationManager.notify(0, n);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Choudhury A. M.
  • 5,152
  • 3
  • 21
  • 21
  • please try to be more concise when you ask questions. You fail to mention *what* isn't working. In fact, you don't even mention something isn't working. Is the `Activity` not being launched? Is the `Notification` not showing? – slinden77 Apr 28 '13 at 09:21
  • 4
    I am pointing out that the purpose of this site is not for you to get your problems fixed, but for others to be able to find a solution to problems as well. I am not poking. Im am sorry I hurt your feelings, but the fact is your question was wrong, the answer was wrong, and all this misleading info will lead to other novice programmers, who have the same issue as you describe, resorting to try solutions that dont work based on the code YOU provided. It's in no case relevant or not if I am an expert or not. Especially not since I am right, your question is vague, and the other answer is wrong. – slinden77 May 08 '13 at 17:18
  • I am going to ask to remove this question and the answer since it's misleading. Have a good day. – slinden77 May 08 '13 at 17:19
  • 1
    changed the question, so that people may understand what is the problem. – Choudhury A. M. May 08 '13 at 19:04
  • Don't forget to register the receiver on Manifest: – lm2a Jul 12 '16 at 15:52
  • I also faced the same issue, in my case I just put notification_id getter than 0. So, change 0 to any number and try it. – Asif Mohammad Mollah Jan 07 '20 at 21:27

15 Answers15

482

The code won't work without an icon. So, add the setSmallIcon call to the builder chain like this for it to work:

.setSmallIcon(R.drawable.icon)

Android Oreo (8.0) and above

Android 8 introduced a new requirement of setting the channelId property by using a NotificationChannel.

NotificationManager mNotificationManager;

NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(mContext.getApplicationContext(), "notify_001");
Intent ii = new Intent(mContext.getApplicationContext(), RootActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, ii, 0);

NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(verseurl);
bigText.setBigContentTitle("Today's Bible Verse");
bigText.setSummaryText("Text in detail");

mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
mBuilder.setContentTitle("Your Title");
mBuilder.setContentText("Your text");
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setStyle(bigText);

mNotificationManager =
    (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

// === Removed some obsoletes
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
    String channelId = "Your_channel_id";
    NotificationChannel channel = new NotificationChannel(
                                        channelId,
                                        "Channel human readable title",
                                        NotificationManager.IMPORTANCE_HIGH);
   mNotificationManager.createNotificationChannel(channel);
  mBuilder.setChannelId(channelId);
}

mNotificationManager.notify(0, mBuilder.build());
Naveed Ahmad
  • 6,627
  • 2
  • 58
  • 83
Choudhury A. M.
  • 5,152
  • 3
  • 21
  • 21
59

Actually the answer by ƒernando Valle doesn't seem to be correct. Then again, your question is overly vague because you fail to mention what is wrong or isn't working.

Looking at your code I am assuming the Notification simply isn't showing.

Your notification is not showing, because you didn't provide an icon. Even though the SDK documentation doesn't mention it being required, it is in fact very much so and your Notification will not show without one.

addAction is only available since 4.1. Prior to that you would use the PendingIntent to launch an Activity. You seem to specify a PendingIntent, so your problem lies elsewhere. Logically, one must conclude it's the missing icon.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
slinden77
  • 3,378
  • 2
  • 37
  • 35
  • i found that issue. But thanks for the proper reply. I really appreciate your help. – Choudhury A. M. May 01 '13 at 19:46
  • 1
    You said that addAction is only available since 4.1 but it is wrong, I used it in 2.3. The reference manual talk about the button not about the notification: "Action buttons won't appear on platforms prior to Android 4.1." you can check here: [AddAction](http://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#addAction%28int,%20java.lang.CharSequence,%20android.app.PendingIntent%29) is included in android.support.v4.app – ƒernando Valle May 01 '13 at 20:13
  • 1
    The OP is using `Notification.Builder`, not `NotificationCompat.Builder`, like you are suggesting. Just because there is a compatibility library and it can be used, doesn't mean the function is avaliable in the normal API. The link you provide actually stipulates this. This question is clearly related to `Notification.Builder`, as the example shows. And the compatibility library probably only included this function after 4.1 was available. Your answer is misleading, because now you suggest it has been available since 2.3. – slinden77 May 01 '13 at 20:45
  • 1
    Sorry if I misspoke, I mean that is possible in 2.3 – ƒernando Valle May 02 '13 at 06:14
  • 5
    Argh the icon!! Didn't even realise it was missing but adding it fixed the problem. Didn't see anything useful in the console about a missing icon, seems to fail silently. – Pete Jun 27 '14 at 07:46
  • There's now NotificationCompat.Action – Daniel Gomez Rico Oct 28 '15 at 00:30
36

You were missing the small icon. I did the same mistake and the above step resolved it.

As per the official documentation: A Notification object must contain the following:

  1. A small icon, set by setSmallIcon()

  2. A title, set by setContentTitle()

  3. Detail text, set by setContentText()

  4. On Android 8.0 (API level 26) and higher, a valid notification channel ID, set by setChannelId() or provided in the NotificationCompat.Builder constructor when creating a channel.

See http://developer.android.com/guide/topics/ui/notifiers/notifications.html

Mikhail Sharin
  • 3,661
  • 3
  • 27
  • 36
21

This tripped me up today, but I realized it was because on Android 9.0 (Pie), Do Not Disturb by default also hides all notifications, rather than just silencing them like in Android 8.1 (Oreo) and before. This doesn't apply to notifications.

I like having DND on for my development device, so going into the DND settings and changing the setting to simply silence the notifications (but not hide them) fixed it for me.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chee-Yi
  • 880
  • 10
  • 17
  • 1
    After more than one hour with no results you saved my day. Thanks! – Jesus Almaral - Hackaprende Sep 25 '20 at 20:04
  • Wow. Half an hour in, pulling my hair, you saved my bacon. Thanks! – Halvtysk Sep 23 '21 at 14:27
  • Aaaaand android tricked us again. Thanks for saving my time! – Dario Coletto Jan 31 '22 at 23:45
  • Ahh, thanks. I'm seeing an issue with Android 9 in DND mode. Is there a link to the official documentation where they've highlighted this restriction? – Shivam Pokhriyal Jun 28 '22 at 12:39
  • I see it here https://developer.android.com/guide/topics/ui/notifiers/notifications#dnd-mode. On Android 8.0 (API level 26) and above, users can additionally allow notifications through for app-specific categories (also known as channels) by overriding Do Not Disturb on a channel-by-channel basis. For example, a payment app might have channels for notifications related to withdrawals and deposits. The user can then choose to allow either withdrawal notifications, deposit notifications, or both when in priority mode. – Shivam Pokhriyal Jun 28 '22 at 12:48
  • It's more evident here https://developer.android.com/training/notify-user/build-notification#system-category which explicitly mentions This information about your notification category is used by the system to make decisions about displaying your notification when the device is in Do Not Disturb mode. – Shivam Pokhriyal Jun 29 '22 at 07:01
14

Creation of notification channels are compulsory for Android versions after Android 8.1 (Oreo) for making notifications visible. If notifications are not visible in your app for Oreo+ Androids, you need to call the following function when your app starts -

private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name,
       importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviours after this
        NotificationManager notificationManager =
        getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
   }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Amit Jaiswal
  • 985
  • 1
  • 9
  • 16
2

You also need to change the build.gradle file, and add the used Android SDK version into it:

implementation 'com.android.support:appcompat-v7:28.0.0'

This worked like a charm in my case.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ashwin Balani
  • 745
  • 7
  • 19
1

I think that you forget the

addAction(int icon, CharSequence title, PendingIntent intent)

Look here: Add Action

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ƒernando Valle
  • 3,634
  • 6
  • 36
  • 58
  • 1
    the method `addAction()` isn't available on `Notification.Builder`. – slinden77 May 09 '13 at 08:51
  • 1
    It does exist, but deprecated. Instead, you can pass an `Action` instance that you can create with `Notification.Action.Builder`. P.S., Always use Compat alternative (i.e., NotificationCompat), since Google tend to patch bugs and provide better compatibility with them – Gökhan Barış Aker Feb 18 '16 at 06:58
  • If you don't want to specify any action, just use `.setContentIntent(null)` with the builder. – Gökhan Barış Aker Feb 18 '16 at 08:16
1

I had the same issue with my Android app. I was trying out notifications and found that notifications were showing on my Android emulator which ran a Android 7.0 (Nougat) system, whereas it wasn't running on my phone which had Android 8.1 (Oreo).

After reading the documentation, I found that Android had a feature called notification channel, without which notifications won't show up on Oreo devices. Below is the link to official Android documentation on notification channels.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

For me it was an issue with deviceToken. Please check if the receiver and sender device token is properly updated in your database or wherever you are accessing it to send notifications.

For instance, use the following to update the device token on app launch. Therefore it will be always updated properly.

// Device token for push notifications
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(
  new OnSuccessListener<InstanceIdResult>() {

    @Override
    public void onSuccess(InstanceIdResult instanceIdResult) {

        deviceToken = instanceIdResult.getToken();

        // Insert device token into Firebase database
        fbDbRefRoot.child("user_detail_profile").child(currentUserId).child("device_token")).setValue(deviceToken)
                .addOnSuccessListener(
                  new OnSuccessListener<Void>() {

                    @Override
                    public void onSuccess(Void aVoid) {

                    }
                });
    }
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DragonFire
  • 3,722
  • 2
  • 38
  • 51
1

I encountered a similar problem to yours and while searching for a solution I found these answers but they weren't as direct as I hoped they would be but it gives an Idea; Your notifications may not be showing because for versions >=8 notifications are done relatively differently there is a NotificationChannel which aids in managing notifications this helped me. Happy coding.

void Note(){
    //Creating a notification channel
    NotificationChannel channel=new NotificationChannel("channel1",
                                                        "hello",
                                                        NotificationManager.IMPORTANCE_HIGH);
    NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.createNotificationChannel(channel); 
    
    //Creating the notification object
    NotificationCompat.Builder notification=new NotificationCompat.Builder(this,"channel1");
    //notification.setAutoCancel(true);
    notification.setContentTitle("Hi this is a notification");
    notification.setContentText("Hello you");
    notification.setSmallIcon(R.drawable.ic_launcher_foreground);   
    
    //make the notification manager to issue a notification on the notification's channel
    manager.notify(121,notification.build());
}
Kimutai
  • 71
  • 4
1

Make sure your notificationId is unique. I couldn't figure out why my test pushes weren't showing up, but it's because the notification ids were generated based on the push content, and since I was pushing the same notification over and over again, the notification id remained the same.

jacoballenwood
  • 2,787
  • 2
  • 24
  • 39
0

If you are on version >= Android 8.1 (Oreo) while using a Notification channel, set its importance to high:

int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
Faisal Naseer
  • 4,110
  • 1
  • 37
  • 55
  • 1
    What do you mean by *"one version >="*? Do you mean *"on version 8.1 (or above)"*? Please respond by [editing your answer](https://stackoverflow.com/posts/57804375/edit), not here in comments (as appropriate). – Peter Mortensen Oct 22 '19 at 06:51
  • @PeterMortensen pardon me for that it was just a type thanks for correcting me – Faisal Naseer Oct 22 '19 at 11:07
0

Notifications may not be shown if you show the notifications rapidly one after the other or cancel an existing one, then right away show it again (e.g. to trigger a heads-up-notification to notify the user about a change in an ongoing notification). In these cases the system may decide to just block the notification when it feels they might become too overwhelming/spammy for the user.

Please note, that at least on stock Android (tested with 10) from the outside this behavior looks a bit random: it just sometimes happens and sometimes it doesn't. My guess is, there is a very short time threshold during which you are not allowed to send too many notifications. Calling NotificationManager.cancel() and then NotificationManager.notify() might then sometimes cause this behavior.

If you have the option, when updating a notification don't cancel it before, but just call NotificationManager.notify() with the updated notification. This doesn't seem to trigger the aforementioned blocking by the system.

ubuntudroid
  • 3,680
  • 6
  • 36
  • 60
0

In addition to the suggestions in the previous answers, when using API 33+ you'll need to declare this dangerous permission in your manifest:

and also request it from the user at runtime.

Oke Uwechue
  • 314
  • 4
  • 14
-2
val pendingIntent = PendingIntent.getActivity(applicationContext, 0, Intent(), 0)

var notification = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
                                    .setContentTitle("Title")
                                    .setContentText("Text")
                                    .setSmallIcon(R.drawable.icon)
                                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                                    .setContentIntent(pendingIntent)
                                    .build()
val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

mNotificationManager.notify(sameId, notification)