I have created a foreground service using the following code which is in the override method OnStartCommand inside a service class called DemoIntentService.cs.
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
Intent notificationIntent = new Intent(this, Java.Lang.Class.FromType(typeof(DemoIntentService)));
PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, notificationIntent, 0);
Notification.Builder notificationBuilder = new Notification.Builder(this, "Example_Service_Channel") .SetSmallIcon(Resource.Drawable.AlertLightFrame) .SetContentTitle(Resources.GetString(Resource.String.DialogAlertTitle)) .SetContentText(Resources.GetString(Resource.String.SelectTextMode)) .SetContentIntent(pendingIntent); Notification notificationAfterBuild = notificationBuilder.Build(); StartForeground(123, notificationAfterBuild); InitializeAlarmManager(); setAlarm(); }
Obviously, the code above is only for Android Oreo 8.0 and above, the service works fine and the notification will not be cleared even though I close the app manually. (That's good, that's what I want !). However, when I use the above code to test on Android Nougat 7.1.1, it would not work.
Firstly, I have researched online they said there is no need to create a notification channel for Android below 8.0, so I remove the "Example_Service_Channel" which is the channelID. The app was deployed successfully, but the notification gone when I kill the app. Second thing, when I removed the channelID, Xamarin throw me a warning said "Notification.Builder.Builder(Context) is obsolete : deprecated" and the line has turn yellow. I ignore the error and deploy the app. The service did run as it is visible in the running service inside the developer options. But when I killed the app, the service and notification gone together. Is there any other way to create a foreground notification service that will never end for Android below 8.0? Thanks for any comment and idea.