#android #kotlin #service
#Android #kotlin #Обслуживание
Вопрос:
Я пытаюсь запустить службу переднего плана, но это не удается
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())
Этот код находится в самом сервисе, поэтому метод Service onCreate вызывает этот блок кода
В прошлый раз это сработало, но когда я удалил приложение и переустановил его, оно начало сбоить.
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)
Что не так с моим кодом?
Комментарии:
1. Вы пробовали добавлять значок в уведомление?
2. @CommonsWare Да, я пробовал с
.setSmallIcon(R.drawable)
, но это тоже не работает.
Ответ №1:
Ответ самостоятельно: Это было из-за содержимого резервной копии. В моем коде я использовал SharedPreference, чтобы проверить, был ли создан канал уведомлений. Но BackupManager
сохранено мое SharedPreference даже после удаления приложения, поэтому при переустановке приложения канал уведомлений не создается. Я изменил AndroidManifest.xml
, как показано ниже, и это очистило мою SharedPreference. Теперь это работает очень хорошо.
<application
android:allowBackup="false"
android:fullBackupOnly="false"
android:fullBackupContent="false"