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);
}