Simplest Way to Implement Notification Channel for Android 8.0 and above


Staring from android 8.0 and above, all notifications MUST be assigned to a notification channel. For each notification channel, you can set a range of behaviors that will be applied to all notifications in that channel, then the user can modify these behaviors and decide which notification channels to pay attention to.

Notification channels code is available on the android studio with API level 26 build tools. Basically, if you are using an older version, please update Android Studio and make sure build tools are higher or equal to API level 26.



How to create Android 8.0 Notification Channel

Notification channel will be ignored for all devices running Android 7 or lower.

To create a notification channel,

  1. you will require NotificaitonChannel Object with a unique ID, CHANNEL NAME and IMPORTANCE LEVEL.
  2. You can also optionally create a channel description, that will be visible to users in the notification settings.
  3. Finally, you register this notification channel to NotificationManager Object using createNotificationChannel()

notification channel illustration
notification channel illustration



Creating Android Project

So now go ahead and create a new Android application project from File > New, fill in all the necessary details.

In your content_main.xml file, or the MainActivity’s layout file, add the following code. We have just created a centered button that will create notification onClick.

<?xml version="1.0" encoding="utf-8"?>;
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main>

    <Button
        android:id="@+id/notify_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@color/colorAccent"
        android:text="Notify via notification Channel"
        android:textColor="#fff" />

</RelativeLayout>;

Create a class called NotificaitonHelper.java and paste the following code. I’m going to explain everything after the code, you must read these codes carefully for you to understand.

package hack.hacksmile.hacksmiletutorials;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.ContextWrapper;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;

public class NotificationHelper extends ContextWrapper {

    private static final String CHANNEL_NAME = "Main Notifications";
    private static final String CHANNEL_DESCRIPTION = "Notification description";
    private static final String CHANNEL_ID = "MyNotificationChannel";
    private static NotificationManager notificationManager;
    private Context base;

    public NotificationHelper(Context base) {
        super(base);

        this.base = base;

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

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createChannel() {
        NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
        notificationChannel.setDescription(CHANNEL_DESCRIPTION);
        notificationChannel.enableVibration(true);
        notificationChannel.enableLights(true);
        notificationChannel.canShowBadge();
        notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        notificationChannel.setLightColor(getResources().getColor(R.color.colorAccent));

        getNotificationManager().createNotificationChannel(notificationChannel);
    }


    public NotificationManager getNotificationManager() {
        if (notificationManager == null) {
            notificationManager = (NotificationManager) base.getSystemService(Context.NOTIFICATION_SERVICE);
        }

        return notificationManager;
    }


    // now lets create notification

    public void notify(String message, String title) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(base, CHANNEL_ID);
        Uri notificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        builder.setContentTitle(title);
        builder.setSmallIcon(R.drawable.ic_launcher_background);
        builder.setContentText(message);
        builder.setSound(notificationUri);
        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(message));


        getNotificationManager().notify(9001, builder.build());
    }


}



As you can see from the above code, we have created a recommended constructor in our NotificaitonHelper class. It’s in this constructor where we are creating our notification channel. Remember, constructors are called as soon as the object has been instantiated. Inside the constructor, please check if android version is greater or equal to 8, if so, create a notification channel, else ignore, Android will handle the rest for you. As we had said earlier, notification channel must be registered to NotificaitionManager object as shown in the code above. In case there is anything you need explanation, kindly ask in the commenting system below, I will reply within minutes or even earlier.

Then add the following code into your MainActivity.java file.

package hack.hacksmile.hacksmiletutorials;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final NotificationHelper notificationHelper = new NotificationHelper(this);

        Button notifyBtn = findViewById(R.id.notify_btn);

        notifyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                notificationHelper.notify("Notification message", "Title");
            }
        });



    }


}


VIDEO