How can I create a notification channel for Android API level < 26 (before Android Oreo)? [closed]

Tags: , , , ,



I am currently working with an Android service: https://developer.android.com/guide/components/services

I am creating a service that has to be a foreground service. But looking at the documentation, a foreground service requires a notification channel.

But a notification channel is only on api 26 or higher. How can i create a notification channel for < 26?

I am stuck with this code

    if (VERSION.SDK_INT >= 26) {
        getSystemService(NotificationManager.class).createNotificationChannel(new NotificationChannel("ServiceWorker", "ServiceWorker", NotificationManager.IMPORTANCE_DEFAULT));
    }

Answer

There is no way to create notification channels for API level < 26, because notification channels were added in API 26.

Fortunately, that means that your code is already correct. You’re already doing the right thing by only creating the channel on API level >= 26.

When you create the notification with NotificationCompat.Builder, you can simply call setChannelId with your string unconditionally, and it will ignore it for you on Android versions where channels are not supported (“No-op on versions prior to Build.VERSION_CODES.O“).

You can then pass the returned notification to startForeground, as described in the guide you linked.



Source: stackoverflow