I'm trying to start foreground service but it fails
val notificationIntent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0)
val builder: NotificationCompat.Builder
builder =
if (Build.VERSION.SDK_INT >= 26) {
val channelId = "noti_channel"
val channel = NotificationChannel(channelId, "Notification Channel", NotificationManager.IMPORTANCE_DEFAULT)
if (!getSharedPreferences("Imhere", Context.MODE_PRIVATE).getBoolean("isNotificationCreated", false)) {
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(channel)
getSharedPreferences("Imhere", Context.MODE_PRIVATE).edit().putBoolean("isNotificationCreated", true).apply()
}
NotificationCompat.Builder(this, channelId)
} else {
NotificationCompat.Builder(this)
}
builder
.setContentTitle("Location Service")
.setContentText("Service running in foreground")
.setContentIntent(pendingIntent)
startForeground(502, builder.build())
This code is in Service itself, so Service onCreate method calls this code block It worked last time, but when I removed the app and reinstalled it, then It started to fail.
2020-08-30 05:08:19.233 706-706/{app package name} E/AndroidRuntime: FATAL EXCEPTION: main
Process: {app package name}, PID: 706
android.app.RemoteServiceException: Bad notification for startForeground
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2141)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:8016)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1076)
What's wrong with my code?