Я ждал своего отчета о сбое, чтобы поделиться решением. Я не получил никакого крушения или ANR почти 20 дней. Я хочу поделиться своим решением. Это может помочь тем, кто сталкивается с этой проблемой.
В onCreate()
метод
- Прежде всего, мое приложение является мультимедийным приложением. Я еще не реализовал медиасессию. Я создаю канал уведомлений в верхней части
onCreate()
. Официальный документ
- Я вызываю
Service.startForeground()
метод после Context.startForegroundService()
метода. По моему prepareAndStartForeground()
методу.
Примечание: я не знаю почему, но ContextCompat.startForegroundService () не работает должным образом.
По этой причине я добавил вручную ту же функцию в свой класс обслуживания вместо вызова ContextCompat.startForegroundService()
private fun startForegroundService(intent: Intent) {
if (Build.VERSION.SDK_INT >= 26) {
context.startForegroundService(intent)
} else {
// Pre-O behavior.
context.startService(intent)
}
}
prepareAndStartForeground()
метод
private fun prepareAndStartForeground() {
try {
val intent = Intent(ctx, MusicService::class.java)
startForegroundService(intent)
val n = mNotificationBuilder.build()
// do sth
startForeground(Define.NOTIFICATION_ID, n)
} catch (e: Exception) {
Log.e(TAG, "startForegroundNotification: " + e.message)
}
}
Это мой onCreate()
override fun onCreate() {
super.onCreate()
createNotificationChannel()
prepareAndStartForeground()
}
Мой onStartCommand()
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent == null) {
return START_STICKY_COMPATIBILITY
} else {
//....
//...
}
return START_STICKY
}
onRebind
, onBind
, onUnbind
методы, подобные этим
internal var binder: IBinder? = null
override fun onRebind(intent: Intent) {
stopForeground(true) // <- remove notification
}
override fun onBind(intent: Intent): IBinder? {
stopForeground(true) // <- remove notification
return binder
}
override fun onUnbind(intent: Intent): Boolean {
prepareAndStartForeground() // <- show notification again
return true
}
Нам нужно что-то очистить, когда onDestroy () вызывает
override fun onDestroy() {
super.onDestroy()
releaseService()
}
private fun releaseService() {
stopMedia()
stopTimer()
// sth like these
player = null
mContext = null
afChangeListener = null
mAudioBecomingNoisy = null
handler = null
mNotificationBuilder = null
mNotificationManager = null
mInstance = null
}
Я надеюсь, что это решение работает правильно для вас.