Search code examples
androidapinotificationsbackwards-compatibility

How to create a Android notification with support to older API levels (e.g. lvl 23)


Maybe this issue is way simpler than I expected it to be: I want to display a notification, created within the onCreate function of an Activity (for debugging reasons).

Android Studio 3.0.1, Api lvl 23 (to support older devices) and running on a Nexus5 device with Api lvl 27.

The Code to display a notification:

    PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
    Notification notification = new NotificationCompat.Builder(this)
            .setTicker("SomethingTicker")
            .setSmallIcon(R.drawable.someImage)
            .setContentTitle("SomeTitle")
            .setContentText("SomeText")
            .setContentIntent(pi)
            .build();

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(001, notification);

Which shows that NotificationCompat.Builder with only the the context is deprecated. I should use a Notification Channel within the newer version.

The issue: To create and register a NotificationChannel I have to use api lvl >27.

What am I missing? And what is the best way


Solution

  • I want to display a notification, created within the onCreate function of an Activity.

    Note that this is an odd time to display a Notification.

    What am I missing?

    You need code to create the NotificationChannel that will only run on Android 8.0+ devices:

    NotificationManager mgr=
      (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    
    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O &&
      mgr.getNotificationChannel(CHANNEL_WHATEVER)==null) {
      mgr.createNotificationChannel(new NotificationChannel(CHANNEL_WHATEVER,
        "Whatever", NotificationManager.IMPORTANCE_DEFAULT));
    }
    

    Then, for all API levels, pass in your channel identifier (here, CHANNEL_WHATEVER) to the NotificationCompat.Builder constructor. On older devices, the channel will be ignored.