[android] Notification not showing in Oreo

Normal Notification Builder doesn't show notifications on Android O.

How could I show notification on Android 8 Oreo?

Is there any new piece of code to add for showing notification on Android O?

This question is related to android android-notifications android-8.0-oreo

The answer is


In android Oreo,notification app is done by using channels and NotificationHelper class.It should have a channel id and channel name.

First u have to create a NotificationHelper Class

public class NotificationHelper extends ContextWrapper {

private static final String EDMT_CHANNEL_ID="com.example.safna.notifier1.EDMTDEV";
private static final String EDMT_CHANNEL_NAME="EDMTDEV Channel";
private NotificationManager manager;

public  NotificationHelper(Context base)
{
    super(base);
    createChannels();
}
private void createChannels()
{
    NotificationChannel edmtChannel=new NotificationChannel(EDMT_CHANNEL_ID,EDMT_CHANNEL_NAME,NotificationManager.IMPORTANCE_DEFAULT);
    edmtChannel.enableLights(true);
    edmtChannel.enableVibration(true);
    edmtChannel.setLightColor(Color.GREEN);
    edmtChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

    getManager().createNotificationChannel(edmtChannel);

}
public NotificationManager getManager()
{
   if (manager==null)
       manager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
   return manager;

}
public NotificationCompat.Builder getEDMTChannelNotification(String title,String body)
{
    return new NotificationCompat.Builder(getApplicationContext(),EDMT_CHANNEL_ID)
            .setContentText(body)
            .setContentTitle(title)
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setAutoCancel(true);
    }
}

Create a button in activity xml file,then In the main activity

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    helper=new NotificationHelper(this);

    btnSend=(Button)findViewById(R.id.btnSend);

    btnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String title="Title";
            String content="Content";
            Notification.Builder builder=helper.getEDMTChannelNotification(title,content);
            helper.getManager().notify(new Random().nextInt(),builder.build());
        }
    });

}

Then run ur project


    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "CHANNEL_ID")
            ........

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

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = "Hello";// The user-visible name of the channel.
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        mNotificationManager.createNotificationChannel(mChannel);
    }
    mNotificationManager.notify(notificationId, notificationBuilder.build());

In addition to this answer, you need to create the notification channel before it can be used.

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

      /* Create or update. */
      NotificationChannel channel = new NotificationChannel("my_channel_01",
          "Channel human readable title", 
          NotificationManager.IMPORTANCE_DEFAULT);
      mNotificationManager.createNotificationChannel(channel);
  }

Also you need to use channels only if your targetSdkVersion is 26 or higher.

If you are using NotificationCompat.Builder, you also need to update to the beta version of the support library: https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0-beta2 (to be able to call setChannelId on the compat builder).

Be careful as this library update raises minSdkLevel to 14.


If you can't get the push notification in 26+ SDK version?

your solution is here:

public static void showNotification(Context context, String title, String messageBody) {

        boolean isLoggedIn = SessionManager.getInstance().isLoggedIn();
        Log.e(TAG, "User logged in state: " + isLoggedIn);

        Intent intent = null;
        if (isLoggedIn) {
            //goto notification screen
            intent = new Intent(context, MainActivity.class);
            intent.putExtra(Extras.EXTRA_JUMP_TO, DrawerItems.ITEM_NOTIFICATION);
        } else {
            //goto login screen
            intent = new Intent(context, LandingActivity.class);
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);

        //Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        //Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_app_notification_icon);

        String channel_id = createNotificationChannel(context);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channel_id)
                .setContentTitle(title)
                .setContentText(messageBody)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody))
                /*.setLargeIcon(largeIcon)*/
                .setSmallIcon(R.drawable.app_logo_color) //needs white icon with transparent BG (For all platforms)
                .setColor(ContextCompat.getColor(context, R.color.colorPrimaryDark))
                .setVibrate(new long[]{1000, 1000})
                .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                .setContentIntent(pendingIntent)
                .setPriority(Notification.PRIORITY_HIGH)
                .setAutoCancel(true);

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify((int) ((new Date(System.currentTimeMillis()).getTime() / 1000L) % Integer.MAX_VALUE) /* ID of notification */, notificationBuilder.build());
    }

public static String createNotificationChannel(Context context) {

        // NotificationChannels are required for Notifications on O (API 26) and above.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            // The id of the channel.
            String channelId = "Channel_id";

            // The user-visible name of the channel.
            CharSequence channelName = "Application_name";
            // The user-visible description of the channel.
            String channelDescription = "Application_name Alert";
            int channelImportance = NotificationManager.IMPORTANCE_DEFAULT;
            boolean channelEnableVibrate = true;
//            int channelLockscreenVisibility = Notification.;

            // Initializes NotificationChannel.
            NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, channelImportance);
            notificationChannel.setDescription(channelDescription);
            notificationChannel.enableVibration(channelEnableVibrate);
//            notificationChannel.setLockscreenVisibility(channelLockscreenVisibility);

            // Adds NotificationChannel to system. Attempting to create an existing notification
            // channel with its original values performs no operation, so it's safe to perform the
            // below sequence.
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            assert notificationManager != null;
            notificationManager.createNotificationChannel(notificationChannel);

            return channelId;
        } else {
            // Returns null for pre-O (26) devices.
            return null;
        }
    }

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channel_id)

-> Here you will get push notification using channel_id in your device which is consist 26+ SDK version.

-> Because, the NotificationCompat.Builder(context) is deprecated method now you will use an updated version which is having two parameters one is context, other is channel_id.

-> NotificationCompat.Builder(context, channel_id) updated method. try it.

-> In 26+ SDK version of device you will create channel_id every time.


Try this Code :

_x000D_
_x000D_
public class FirebaseMessagingServices extends com.google.firebase.messaging.FirebaseMessagingService {_x000D_
    private static final String TAG = "MY Channel";_x000D_
    Bitmap bitmap;_x000D_
_x000D_
    @Override_x000D_
    public void onMessageReceived(RemoteMessage remoteMessage) {_x000D_
        super.onMessageReceived(remoteMessage);_x000D_
        Utility.printMessage(remoteMessage.getNotification().getBody());_x000D_
_x000D_
        // Check if message contains a data payload._x000D_
        if (remoteMessage.getData().size() > 0) {_x000D_
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());_x000D_
_x000D_
            String title = remoteMessage.getData().get("title");_x000D_
            String body = remoteMessage.getData().get("body");_x000D_
            String message = remoteMessage.getData().get("message");_x000D_
            String imageUri = remoteMessage.getData().get("image");_x000D_
            String msg_id = remoteMessage.getData().get("msg-id");_x000D_
          _x000D_
_x000D_
            Log.d(TAG, "1: " + title);_x000D_
            Log.d(TAG, "2: " + body);_x000D_
            Log.d(TAG, "3: " + message);_x000D_
            Log.d(TAG, "4: " + imageUri);_x000D_
          _x000D_
_x000D_
            if (imageUri != null)_x000D_
                bitmap = getBitmapfromUrl(imageUri);_x000D_
_x000D_
            }_x000D_
_x000D_
            sendNotification(message, bitmap, title, msg_id);_x000D_
                    _x000D_
        }_x000D_
_x000D_
_x000D_
    }_x000D_
_x000D_
    private void sendNotification(String message, Bitmap image, String title,String msg_id) {_x000D_
        int notifyID = 0;_x000D_
        try {_x000D_
            notifyID = Integer.parseInt(msg_id);_x000D_
        } catch (NumberFormatException e) {_x000D_
            e.printStackTrace();_x000D_
        }_x000D_
_x000D_
        String CHANNEL_ID = "my_channel_01";            // The id of the channel._x000D_
        Intent intent = new Intent(this, HomeActivity.class);_x000D_
        intent.putExtra("title", title);_x000D_
        intent.putExtra("message", message);_x000D_
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);_x000D_
_x000D_
_x000D_
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,_x000D_
                PendingIntent.FLAG_ONE_SHOT);_x000D_
_x000D_
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);_x000D_
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "01")_x000D_
                .setContentTitle(title)_x000D_
                .setSmallIcon(R.mipmap.ic_notification)_x000D_
                .setStyle(new NotificationCompat.BigTextStyle()_x000D_
                        .bigText(message))_x000D_
                .setContentText(message)_x000D_
                .setAutoCancel(true)_x000D_
                .setSound(defaultSoundUri)_x000D_
                .setChannelId(CHANNEL_ID)_x000D_
                .setContentIntent(pendingIntent);_x000D_
_x000D_
        if (image != null) {_x000D_
            notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle()   //Set the Image in Big picture Style with text._x000D_
                    .bigPicture(image)_x000D_
                    .setSummaryText(message)_x000D_
                    .bigLargeIcon(null));_x000D_
        }_x000D_
_x000D_
_x000D_
        NotificationManager notificationManager =_x000D_
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);_x000D_
_x000D_
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {       // For Oreo and greater than it, we required Notification Channel._x000D_
           CharSequence name = "My New Channel";                   // The user-visible name of the channel._x000D_
            int importance = NotificationManager.IMPORTANCE_HIGH;_x000D_
_x000D_
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,name, importance); //Create Notification Channel_x000D_
            notificationManager.createNotificationChannel(channel);_x000D_
        }_x000D_
_x000D_
        notificationManager.notify(notifyID /* ID of notification */, notificationBuilder.build());_x000D_
    }_x000D_
_x000D_
    public Bitmap getBitmapfromUrl(String imageUrl) {     //This method returns the Bitmap from Url;_x000D_
        try {_x000D_
            URL url = new URL(imageUrl);_x000D_
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();_x000D_
            connection.setDoInput(true);_x000D_
            connection.connect();_x000D_
            InputStream input = connection.getInputStream();_x000D_
            Bitmap bitmap = BitmapFactory.decodeStream(input);_x000D_
            return bitmap;_x000D_
_x000D_
        } catch (Exception e) {_x000D_
            // TODO Auto-generated catch block_x000D_
            e.printStackTrace();_x000D_
            return null;_x000D_
_x000D_
        }_x000D_
_x000D_
    }_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_


NotificationCompat.Builder(Context context)

already deprecated for version greater than or equal android Oreo. You can change implementation into using

NotificationCompat.Builder(Context context, String channelId)

Following method will show Notification, having big text and freeze enabled( Notification will not get removed even after user swipes ). We need NotificationManager service

public static void showNotificationOngoing(Context context,String title) {
        NotificationManager notificationManager =
                (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
                new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

        Notification.Builder notificationBuilder = new Notification.Builder(context)
                .setContentTitle(title + DateFormat.getDateTimeInstance().format(new Date()) + ":" + accuracy)
                .setContentText(addressFragments.toString())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(contentIntent)
                .setOngoing(true)
                .setStyle(new Notification.BigTextStyle().bigText(addressFragments.toString()))
                .setAutoCancel(true);
        notificationManager.notify(3, notificationBuilder.build());
}

Method to Remove Notifications

public static void removeNotification(Context context){
    NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
    notificationManager.cancelAll();
}

Source Link


Well In my case, I have Android 8.1.0 and model number vivo1811, and I have tried with all of the above solutions but Nothing works.

So At last, I have written to Firebase Support then on further debugging, I was getting this- "Failed to broadcast to stopped app ": Ensure that app has not been force stopped" .

And this was the reply from Firebase team ->

This is a known issue that is caused by a battery optimization implemented by some OEMs. When an app is swiped away in the app switcher, the application is treated as if it was force-stopped, which is not the default Android behavior. The unfortunate side effect of this is that it can cause the FCM service for your app to stop running. We are working to improve this behavior from our end, but the actual fix has to come from the OEM side.

Here OEM stands for Original Equipment Manufacturer.


Here i post some quick solution function with intent handling

public void showNotification(Context context, String title, String body, Intent intent) {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    int notificationId = 1;
    String channelId = "channel-01";
    String channelName = "Channel Name";
    int importance = NotificationManager.IMPORTANCE_HIGH;

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel mChannel = new NotificationChannel(
                channelId, channelName, importance);
        notificationManager.createNotificationChannel(mChannel);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(title)
            .setContentText(body);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addNextIntent(intent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
            0,
            PendingIntent.FLAG_UPDATE_CURRENT
    );
    mBuilder.setContentIntent(resultPendingIntent);

    notificationManager.notify(notificationId, mBuilder.build());
}

Here's how you do it

private fun sendNotification() {
    val notificationId = 100
    val chanelid = "chanelid"
    val intent = Intent(this, MainActivity::class.java)
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
    val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // you must create a notification channel for API 26 and Above
        val name = "my channel"
        val description = "channel description"
        val importance = NotificationManager.IMPORTANCE_DEFAULT
        val channel = NotificationChannel(chanelid, name, importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        val notificationManager = getSystemService(NotificationManager::class.java)
        notificationManager.createNotificationChannel(channel)
    }

    val mBuilder = NotificationCompat.Builder(this, chanelid)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("Want to Open My App?")
            .setContentText("Open my app and see good things")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true) // cancel the notification when clicked
            .addAction(R.drawable.ic_check, "YES", pendingIntent) //add a btn to the Notification with a corresponding intent

    val notificationManager = NotificationManagerCompat.from(this);
    notificationManager.notify(notificationId, mBuilder.build());
}

Read full tutorial at => https://developer.android.com/training/notify-user/build-notification


You Need to create a notification channel for API level above 26(oreo).

`NotificationChannel channel = new NotificationChannel(STRING_ID,CHANNEL_NAME,NotificationManager.IMPORTANCE_HIGH);

STRING_ID = string notification channelid is the same as in Notification.Builder like this

`Notification notification = new Notification.Builder(this,STRING_ID)
            .setSmallIcon(android.R.drawable.ic_menu_help)
            .setContentTitle("Hello Notification")
            .setContentText("It is Working")
            .setContentIntent(pendingIntent)
            .build();`

Channel id in the notification and in the notification should be same Whole code is like this.. `

@RequiresApi(api = Build.VERSION_CODES.O)
  private void callNotification2() {

    Intent intent = new Intent(getApplicationContext(),MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,11, 
    intent,PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = new Notification.Builder(this,"22")
            .setSmallIcon(android.R.drawable.ic_menu_help)
            .setContentTitle("Hello Notification")
            .setContentText("It is Working")
            .setContentIntent(pendingIntent)
            .build();
    NotificationChannel channel = new 
    NotificationChannel("22","newName",NotificationManager.IMPORTANCE_HIGH);
    NotificationManager manager = (NotificationManager) 
    getSystemService(NOTIFICATION_SERVICE);
    manager.createNotificationChannel(channel);
    manager.notify(11,notification);

    }'

I have faced the problem but found a unique solution.
for me this was the old code

String NOTIFICATION_CHANNEL_ID = "com.codedevtech.emplitrack";

and the working code is

String NOTIFICATION_CHANNEL_ID = "emplitrack_channel";

may be the channel id should not contain dot '.'


First of all, if you dont know, from Android Oreo i.e API level 26 it's compulsory that notifications are resgitered with a channel.

In that case many tutorials might confuse you because they show different example for notification above oreo and below.

So here is is a common code which runs on both above and below oreo:

String CHANNEL_ID = "MESSAGE";
String CHANNEL_NAME = "MESSAGE";

NotificationManagerCompat manager = NotificationManagerCompat.from(MainActivity.this);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME,
    NotificationManager.IMPORTANCE_DEFAULT);
    manager.createNotificationChannel(channel);
}

Notification notification = new NotificationCompat.Builder(MainActivity.this,CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_android_black_24dp)
        .setContentTitle(TitleTB.getText().toString())
        .setContentText(MessageTB.getText().toString())
        .build();
manager.notify(getRandomNumber(), notification); // In case you pass a number instead of getRandoNumber() then the new notification will override old one and you wont have more then one notification so to do so u need to pass unique number every time so here is how we can do it by "getRandoNumber()"
private static int getRandomNumber() {
    Date dd= new Date();
    SimpleDateFormat ft =new SimpleDateFormat ("mmssSS");
    String s=ft.format(dd);
    return Integer.parseInt(s);
}

Video Tutorial: YOUTUBE VIDEO

In case you want to download this demo: GitHub Link


public class MyFirebaseMessagingServices extends FirebaseMessagingService {
    private NotificationChannel mChannel;
    private NotificationManager notifManager;
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getData().size() > 0) {
            try {
                JSONObject jsonObject = new JSONObject(remoteMessage.getData());
                displayCustomNotificationForOrders(jsonObject.getString("title"), jsonObject.getString("description"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void displayCustomNotificationForOrders(String title, String description) {
        if (notifManager == null) {
            notifManager = (NotificationManager) getSystemService
                    (Context.NOTIFICATION_SERVICE);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationCompat.Builder builder;
            Intent intent = new Intent(this, Dashboard.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent;
            int importance = NotificationManager.IMPORTANCE_HIGH;
            if (mChannel == null) {
                mChannel = new NotificationChannel
                        ("0", title, importance);
                mChannel.setDescription(description);
                mChannel.enableVibration(true);
                notifManager.createNotificationChannel(mChannel);
            }
            builder = new NotificationCompat.Builder(this, "0");

            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                    Intent.FLAG_ACTIVITY_SINGLE_TOP);
            pendingIntent = PendingIntent.getActivity(this, 1251, intent, PendingIntent.FLAG_ONE_SHOT);
            builder.setContentTitle(title)  
                    .setSmallIcon(getNotificationIcon()) // required
                    .setContentText(description)  // required
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setLargeIcon(BitmapFactory.decodeResource
                            (getResources(), R.mipmap.logo))
                    .setBadgeIconType(R.mipmap.logo)
                    .setContentIntent(pendingIntent)
                    .setSound(RingtoneManager.getDefaultUri
                            (RingtoneManager.TYPE_NOTIFICATION));
            Notification notification = builder.build();
            notifManager.notify(0, notification);
        } else {

            Intent intent = new Intent(this, Dashboard.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = null;

            pendingIntent = PendingIntent.getActivity(this, 1251, intent, PendingIntent.FLAG_ONE_SHOT);

            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setContentTitle(title)
                    .setContentText(description)
                    .setAutoCancel(true)
                    .setColor(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary))
                    .setSound(defaultSoundUri)
                    .setSmallIcon(getNotificationIcon())
                    .setContentIntent(pendingIntent)
                    .setStyle(new NotificationCompat.BigTextStyle().setBigContentTitle(title).bigText(description));

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(1251, notificationBuilder.build());
        }
    }

    private int getNotificationIcon() {
        boolean useWhiteIcon = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
        return useWhiteIcon ? R.mipmap.logo : R.mipmap.logo;
    }
}

The below piece of code is working for me in the Oreo, you can try this. hope it will work for you

private void sendNotification(Context ctx, String title, int notificationNumber, String message, String subtext, Intent intent) {
try {

            PendingIntent pendingIntent = PendingIntent.getActivity(ctx, notificationNumber, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            Uri url = null;           
            NotificationCompat.Builder notificationBuilder = null;
            try {
                if (Build.VERSION.SDK_INT >= 26) {

                    try{
                        NotificationManager notificationManager = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
                        notificationManager.deleteNotificationChannel(CHANNEL_ID_1);
                        notificationManager.deleteNotificationChannel(CHANNEL_ID_2);

                        if(!intent.getStringExtra("type").equalsIgnoreCase(""+TYPE_REQUEST)){
                            NotificationChannel breaking = new NotificationChannel(CHANNEL_ID_1, CHANNEL_ID_1_NAME, NotificationManager.IMPORTANCE_HIGH);
                            breaking.setShowBadge(false);
                            breaking.enableLights(true);
                            breaking.enableVibration(true);
                            breaking.setLightColor(Color.WHITE);
                            breaking.setVibrationPattern(new long[]{100, 200, 100, 200, 100, 200, 100});
                            breaking.setSound(url,new AudioAttributes.Builder().build());

                            notificationBuilder = new NotificationCompat.Builder(this,CHANNEL_ID_1)
                                    .setSmallIcon(R.mipmap.ic_launcher);
                            notificationManager.createNotificationChannel(breaking);

                        }else{

                            NotificationChannel politics = new NotificationChannel(CHANNEL_ID_2,CHANNEL_ID_2_NAME, NotificationManager.IMPORTANCE_DEFAULT);
                            politics.setShowBadge(false);
                            politics.enableLights(true);
                            politics.enableVibration(true);
                            politics.setLightColor(Color.BLUE);
                            politics.setVibrationPattern(new long[]{100, 200, 100, 200, 100});
                            politics.setSound(url,new AudioAttributes.Builder().build());

                            notificationBuilder = new NotificationCompat.Builder(this,CHANNEL_ID_2)
                                    .setSmallIcon(R.mipmap.ic_launcher);
                            notificationManager.createNotificationChannel(politics);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                } else {
                    notificationBuilder = new NotificationCompat.Builder(ctx)
                            .setSmallIcon(R.mipmap.ic_launcher);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (notificationBuilder == null) {
                notificationBuilder = new NotificationCompat.Builder(ctx)
                        .setSmallIcon(R.mipmap.ic_launcher);
            }


            notificationBuilder.setContentTitle(title);          
            notificationBuilder.setSubText(subtext);
            notificationBuilder.setAutoCancel(true);

            notificationBuilder.setContentIntent(pendingIntent);
            notificationBuilder.setNumber(notificationNumber);
            NotificationManager notificationManager =
                    (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(notificationNumber, notificationBuilder.build());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

Use this class for Android 8 Notification

public class NotificationHelper {

private Context mContext;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mBuilder;
public static final String NOTIFICATION_CHANNEL_ID = "10001";

public NotificationHelper(Context context) {
    mContext = context;
}

/**
 * Create and push the notification 
 */
public void createNotification(String title, String message)
{    
    /**Creates an explicit intent for an Activity in your app**/
    Intent resultIntent = new Intent(mContext , SomeOtherActivity.class);
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
            0 /* Request code */, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder = new NotificationCompat.Builder(mContext);
    mBuilder.setSmallIcon(R.mipmap.ic_launcher);
    mBuilder.setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(false)
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
            .setContentIntent(resultPendingIntent);

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

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
    {
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        assert mNotificationManager != null;
        mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
        mNotificationManager.createNotificationChannel(notificationChannel);
    }
    assert mNotificationManager != null;
    mNotificationManager.notify(0 /* Request Code */, mBuilder.build());
  }
}

This is bug in firebase api version 11.8.0, So if you reduce API version you will not face this issue.


Android Notification Demo App for Android O as well as lower API versions. Here is best demo app on GitHub-Demo 1 and GitHub-Demo 2.

enter image description here


I was having the same issue on Oreo and discovered that if you first create your Channel with NotificationManager.IMPORTANCE_NONE, then update it later, the channel will retain the original importance level.

This is backed up by the Google Notification training documentation which states:

After you create a notification channel, you cannot change the notification behaviors—the user has complete control at that point.

Removing and re-installing the app will allow you to reset the channel behaviors.

Best to avoid using IMPORTANCE_NONE unless you want to suppress the notifications for that Channel, ie, to make use of silent notifications.


CHANNEL_ID in NotificationChannel and Notification.Builder must be the same, try this code:

String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Solveta Unread", NotificationManager.IMPORTANCE_DEFAULT);


Notification.Builder notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID);

For anyone struggling with this after trying the above solutions, ensure that the channel id used when creating the notification channel is identical to the channel id you set in the Notification builder.

const val CHANNEL_ID = "EXAMPLE_CHANNEL_ID"

// create notification channel
val notificationChannel = NotificationChannel(CHANNEL_ID, 
NOTIFICATION_NAME, NotificationManager.IMPORTANCE_HIGH)

// building notification
NotificationCompat.Builder(context)
                    .setSmallIcon(android.R.drawable.ic_input_add)
                    .setContentTitle("Title")
                    .setContentText("Subtitle")   
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setChannelId(CHANNEL_ID)

private void addNotification() {
                NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle("Notifications Example")
                .setContentText("This is a test notification");
                Intent notificationIntent = new Intent(this, MainActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
                builder.setContentIntent(contentIntent);
                // Add as notification
                NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
                {
                NotificationChannel nChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH);
                nChannel.enableLights(true);
                assert manager != null;
                builder.setChannelId(NOTIFICATION_CHANNEL_ID);
                manager.createNotificationChannel(nChannel);
                }
                assert manager != null;
                manager.notify(0, builder.build());
    }

fun pushNotification(message: String?, clickAtion: String?) {
        val ii = Intent(clickAtion)
        ii.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        val pendingIntent = PendingIntent.getActivity(this, REQUEST_CODE, ii, PendingIntent.FLAG_ONE_SHOT)

        val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

        val largIcon = BitmapFactory.decodeResource(applicationContext.resources,
                R.mipmap.ic_launcher)


        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        val channelId = "default_channel_id"
        val channelDescription = "Default Channel"
// Since android Oreo notification channel is needed.
//Check if notification channel exists and if not create one
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            var notificationChannel = notificationManager.getNotificationChannel(channelId)
            if (notificationChannel != null) {
                val importance = NotificationManager.IMPORTANCE_HIGH //Set the importance level
                notificationChannel = NotificationChannel(channelId, channelDescription, importance)
               // notificationChannel.lightColor = Color.GREEN //Set if it is necesssary
                notificationChannel.enableVibration(true) //Set if it is necesssary
                notificationManager.createNotificationChannel(notificationChannel)


                val noti_builder = NotificationCompat.Builder(this)
                        .setContentTitle("MMH")
                        .setContentText(message)
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setChannelId(channelId)
                        .build()
                val random = Random()
                val id = random.nextInt()
                notificationManager.notify(id,noti_builder)

            }

        }
        else
        {
            val notificationBuilder = NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher).setColor(resources.getColor(R.color.colorPrimary))
                    .setVibrate(longArrayOf(200, 200, 0, 0, 0))
                    .setContentTitle(getString(R.string.app_name))

                    .setLargeIcon(largIcon)
                    .setContentText(message)
                    .setAutoCancel(true)
                    .setStyle(NotificationCompat.BigTextStyle().bigText(message))
                    .setSound(soundUri)
                    .setContentIntent(pendingIntent)


            val random = Random()
            val id = random.nextInt()
            notificationManager.notify(id, notificationBuilder.build())

        }



    }

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-notifications

startForeground fail after upgrade to Android 8.1 NotificationCompat.Builder deprecated in Android O Notification not showing in Oreo Firebase FCM notifications click_action payload Notification bar icon turns white in Android 5 Lollipop INSTALL_FAILED_DUPLICATE_PERMISSION... C2D_MESSAGE Android: Test Push Notification online (Google Cloud Messaging) How to display multiple notifications in android Android Notification Sound How to create a notification with NotificationCompat.Builder?

Examples related to android-8.0-oreo

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent Setting up Gradle for api 26 (Android) Context.startForegroundService() did not then call Service.startForeground() Notification not showing in Oreo