Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad notification for startForeground in Android app

I am developing a service using Xamarin Android 3.5. Our app targets Android 8.1 (API 27 - Oreo). I want the service to run as a foreground service. However I am getting the following error when I run the service.

Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=1 contentView=null vibrate=null sound=null defaults=0x0 flags=0x42 color=0x00000000 vis=PRIVATE)

Here is the code for the service.

public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
  base.OnStartCommand(intent, flags, startId);
  var context = Application.Context;
  const int pendingIntentId = 0;
  PendingIntent pendingIntent = PendingIntent.GetActivity(context, pendingIntentId, intent, PendingIntentFlags.OneShot);
  var notification = new NotificationCompat.Builder(context)
    .SetContentTitle("Testing")
    .SetContentText("location tracking has begun.")
    .SetSmallIcon(Resource.Drawable.icon)
    .SetContentIntent(pendingIntent)
    .SetOngoing(true)
    .Build();
    // Enlist this instance of the service as a foreground service
    const int Service_Running_Notification_ID = 935;
    StartForeground(Service_Running_Notification_ID, notification);
    return StartCommandResult.NotSticky;
}

I have updated the AndroidManifest.xml with the following.

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

In the MainActivity.cs I have the follwing code which we use to create a notification channel for sending app notifications (and which correctly creates the notification channel).

private void CreateNotificationChannel()
{
  if (Build.VERSION.SdkInt < BuildVersionCodes.O)
  {
    // Notification channels are new in API 26 (and not a part of the
    // support library). There is no need to create a notification 
    // channel on older versions of Android.
    return;
  }
  var channel = new NotificationChannel(ApplicationConstants.ChannelId, ApplicationConstants.ChannelName, NotificationImportance.Default)
  {
    Description = ApplicationConstants.ChannelDescription
  };
  var notificationManager = (NotificationManager)GetSystemService(NotificationService);
  notificationManager.CreateNotificationChannel(channel);
}
like image 323
DomBurf Avatar asked Jul 15 '19 09:07

DomBurf


People also ask

How do I get a notification channel ID?

To turn on the setting for a development device running Android 8.0 (API level 26), navigate to Settings > Developer options and enable Show notification channel warnings.

How do you stop foreground service?

The service must stop itself by calling stopSelf(), or another component can stop it by calling stopService(). Once requested to stop with stopSelf() or stopService(), the system destroys the service as soon as possible.

What is NotificationCompat builder?

public class NotificationCompat.Builder. Builder class for NotificationCompat objects. Allows easier control over all the flags, as well as help constructing the typical notification layouts. On platform versions that don't offer expanded notifications, methods that depend on expanded notifications have no effect.


2 Answers

For Xamarin.Forms and Xamarin.Android

========Put this code in public override StartCommandResult OnStartCommand ===========

 if (Build.VERSION.SdkInt >= Build.VERSION_CODES.O)
      RegisterForegroundServiceO();
  else { RegisterForegroundService(); }

========================================END=============================

 void RegisterForegroundService()
        {
            var notification = new Notification.Builder(this)
                .SetContentTitle(Resources.GetString(Resource.String.app_name))
                .SetContentText(Resources.GetString(Resource.String.notification_text))
                .SetSmallIcon(Resource.Drawable.icon_userProfile)
                .SetContentIntent(BuildIntentToShowMainActivity())
                .SetOngoing(true)
                .Build();
            const int Service_Running_Notification_ID = 936;
            StartForeground(Service_Running_Notification_ID, notification);
        }


void RegisterForegroundServiceO()
    {
        String NOTIFICATION_CHANNEL_ID = "com.Your.project.id";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Your Channel Name", NotificationManager.ImportanceHigh);

        NotificationManager manager = (NotificationManager)GetSystemService(Context.NotificationService);

        manager.CreateNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

        Notification notification= notificationBuilder.SetOngoing(true)
            .SetContentTitle(Resources.GetString(Resource.String.app_name))
            .SetContentText(Resources.GetString(Resource.String.notification_text))
            .SetSmallIcon(Resource.Drawable.icon_userProfile)
            .SetContentIntent(BuildIntentToShowMainActivity())
            .SetOngoing(true)
            .Build();

        const int Service_Running_Notification_ID = 936;
        StartForeground(Service_Running_Notification_ID, notification);
    }

Happy Coding. :-)

like image 167
Ripdaman Singh Avatar answered Sep 21 '22 16:09

Ripdaman Singh


invalid channel for service notification

You are creating a notification channel but never assigning it in your NotificationCompat.Builder:

var notification = new NotificationCompat.Builder(context)
   ~~~
   .SetChannelId(ApplicationConstants.ChannelId)
   ~~~

Docs: https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder

like image 31
SushiHangover Avatar answered Sep 19 '22 16:09

SushiHangover