I start a foreground service, and it's working for Android 8 and below; however, it gives RemoteServiceException for Android 9 and Android 10
I called startMyForegroundService() in onCreate and onStartCommand.
private void startMyForegroundService() {
try {
//prevent 5 seconds Context.startForegroundService() did not then call Service.startForeground()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String CHANNEL_ID = "my_service";
String CHANNEL_NAME = "My Background Service";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_NONE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(channel);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setPriority(NotificationManager.IMPORTANCE_HIGH)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
} else {
startForeground(1, new Notification());
}
} catch (Exception ex) {
//Crashlytics.logException(ex);
Log.e(StandOutWindow.class.getName(), "Service manager can't start service ");
}
}
Exception
Fatal Exception: android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x60 color=0x00000000 vis=SECRET internalType=0 internalPriority=0 internalGroupPriority=0 internalFlag=0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1965)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7081)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:536)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:928)
If you need more information, please let me know.
It turns out that there's another method that create notification, so I just have to create channel before create notification.
User contributions licensed under CC BY-SA 3.0