Search code examples
androidandroid-notificationsandroid-8.1-oreonotification-channel

NotificationCompat.Builder() not accepting Channel Id as argument


I know this question has been asked several times before. But none of the solutions worked for me. That's why I would like to ask the question again. The following line only accepts NotificationCompat.Builder(context) :

 NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, ADMIN_CHANNEL_ID)  // Getting error

I have fulfilled:

  • importing android.support.v4.app.NotificationCompat
  • My support libraries version is above 25

    implementation group: 'com.android.support', name: 'appcompat-v7', version: '27.1.1'

  • Compile & Target sdk is above 25

    android { compileSdkVersion(27) buildToolsVersion '27.0.3' flavorDimensions 'default' dataBinding { enabled = true } defaultConfig { applicationId('something') minSdkVersion(16) targetSdkVersion(27) versionCode(1) versionName('1.0.0') testInstrumentationRunner('android.support.test.runner.AndroidJUnitRunner') multiDexEnabled true } But still getting the error. What should I do to fix this? Please help.


Solution

  • Solution:

    On Android 8.0 (Oreo) you must have something called as a NotificationChannel So try the below implementation:

    Step1: Create Notification Channel

    private void createNotificationChannel() {
    
        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);
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
    

    Finally: Then your Notification:

     NotificationCompat.Builder mBuilder =   new NotificationCompat.Builder(activity)
                    .setSmallIcon(R.drawable.ic_launcher_background) // notification icon
                    .setContentTitle("Notification!") // title for notification
                    .setContentText("Hello word") // message for notification
                    .setAutoCancel(true); // clear notification after click
    Intent intent = new Intent(activity, RecorderActivity.class);
    PendingIntent pi = PendingIntent.getActivity(activity,0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    mBuilder.setContentIntent(pi);
    notificationManager.notify(1, mBuilder.build());
    

    Please compare this with Yours and see if it works

    Try this, Hope it helps.