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?
Self answer:
It was because of backup content.
In my code, I used SharedPreference to check if the notification channel was created. But BackupManager
saved my SharedPreference even after app was removed, so when the app is reinstalled, notification channel is not created.
I changed AndroidManifest.xml
as shown below and it cleared my SharedPreference. Now it works very well.
<application
android:allowBackup="false"
android:fullBackupOnly="false"
android:fullBackupContent="false"