MediaBrowserServiceCompat not stopping correctly
Hi. I am using MediaBrowserServiceCompat, ExoPlayer, and MediaBrowserCompat to connect to the service. I followed the uamp project in regard how they release service.
I am stopping player onTaskRemoved (if i want service and audio to stop when app is closed). Which gets to onPlayerStateChanged and closes notification. There i am stopping foreground service, and call stopSelf().
Actually I tried most combinations of these lines of code on different steps:
exoPlayer.stop()
exoPlayer.clearMediaItems()
exoPlayer.removeListener(radioPlayerEventListener)
exoPlayer.release()
stopForeground(Service.STOP_FOREGROUND_REMOVE)
stopSelf()
radioNotificationManager.removeNotification()
mediaSession.run {
isActive = false
release()
}
serviceJob.cancel()
I also disconnect controller (otherwise service's onDestroy() won't be called)
fun disconnectBrowser(){
mediaController.unregisterCallback(mediaControllerCallback)
mediaBrowser.disconnect()
}
But service and application just does not stop on certain conditions.
- If i am closing an application while exoplayer plays audio (and i stop player on taskRemoved) service does not stop.
- If I close the app and don't stop player on taskRemoved, but instead use notification to stop player, and then remove notification, service also does not stop.
So service is destroyed correctly only in case when stopForeground(STOP_FOREGROUND_DETACH) is called before closing the app and exoplayer was paused before that.
I am using hilt injection for ExoPlayer instance:
@Module
@InstallIn(ServiceComponent::class)
object ServiceModule {
@Provides
@ServiceScoped
fun providesAudioAttributes() = AudioAttributes.Builder()
.setContentType(C.AUDIO_CONTENT_TYPE_MUSIC)
.setUsage(C.USAGE_MEDIA)
.build()
@Provides
@ServiceScoped
fun providesExoPlayer (
@ApplicationContext app : Context,
audioAttributes: AudioAttributes,
renderersFactory: DefaultRenderersFactory
) = ExoPlayer.Builder(app, renderersFactory)
.setAudioAttributes(audioAttributes, true)
.setHandleAudioBecomingNoisy(true)
.build()
@Provides
@ServiceScoped
fun providesDataSourceFactory (
@ApplicationContext app : Context
) = DefaultDataSource.Factory(app)
@Provides
@ServiceScoped
fun providesRendersFactory(
@ApplicationContext app : Context,
exoRecord: ExoRecord
) = object : DefaultRenderersFactory(app){
override fun buildAudioSink(
context: Context,
enableFloatOutput: Boolean,
enableAudioTrackPlaybackParams: Boolean,
enableOffload: Boolean
): AudioSink {
return DefaultAudioSink.Builder()
.setAudioCapabilities(getCapabilities(app))
.setEnableFloatOutput(true)
.setEnableAudioTrackPlaybackParams(true)
.build()
}
}
}
And for MediaBrowserCompat :
@Provides
@Singleton
fun providesRadioServiceConnection(
@ApplicationContext app : Context
) = RadioServiceConnection(app)
The only working solution now seems to be just to kill process (put it in service's onDestroy():
android.os.Process.killProcess(android.os.Process.myPid())
Is it ok when I assign this to me again? I'm asking because you closed the old bug reporting the same thing and you created a new one. If you would like someone else to be assigned to this bug let us know. As you prefer.
Generally this report is about MediaBrowserServiceCompat of the media1 library. In this service the app needs to manage foreground service state, notification and player state on their own. So if there are problems around these things, it is mostly the problem of the app implementation because the complicated things have to be done by the app.
Aside: That's one of the reason why we do that now in the library for Media3 with MediaLibraryService.
To the best of my knowledge the player state and setup does not have an impact on whether a service can be terminated or not. This is only the case if the the app creates such a relationship between player state and service state. For MediaBrowserServiceImpl there is no such direct relationship that I would know of. However, I'd make sure to have the player paused and stopped. Your app may have the service in the foreground when not paused, so pausing seems good in general.
Second I'd make sure that all clients are unbound from the service. You can track onBind/onUnbind/onRebind for that to know. When a client is bound to the service the service is never stopped.
Third, I'd make sure that the service is not in foreground and the notification has been removed, when attempting to terminate the service.
Fourth, make sure that the session is released when trying to terminate the service. Use adb shell dumpsys media_session to verify.
That's all I know and what could think of prevents a service from being terminated properly.
Hi, thanks for your answer. I tried to put problem in more structured way this time, that's all. Yes, I was thinking of updating to MediaLibraryService, but it is marked as unstable api and i see there are leaking reports too. First report of MediaBrowserServiceCompat leak i believe was of 2016, so I hope the problem is not here now. Canary does detect service as a leak though but its probably because of some bug in my app. I can't detach foreground if exoplayer is playing audio. I guess its the only impact on service. I was checking foreground like this and it seems to give correct info:
@Suppress("DEPRECATION")
fun <T> Context.isServiceForegrounded(service: Class<T>) =
(getSystemService(ACTIVITY_SERVICE) as? ActivityManager)
?.getRunningServices(Integer.MAX_VALUE)
?.find { it.service.className == service.name }
?.foreground == true
I will try with onBind and "adb shell dumpsys media_session" and report back
It seems service is getting only one binding intent, from mediaBrowser. I connect on start activity and unbind on stop, as per documentation.
I run adb command after closing an app (and service not being destroyed correctly, therefore alive):
4 sessions listeners.
Global priority session is com.android.server.telecom/HeadsetMediaButton (userId=0)
HeadsetMediaButton com.android.server.telecom/HeadsetMediaButton (userId=0)
ownerPid=593, ownerUid=1000, userId=0
package=com.android.server.telecom
launchIntent=null
mediaButtonReceiver=null
active=false
flags=65537
rating type=0
controllers: 0
state=null
audioAttrs=AudioAttributes: usage=USAGE_VOICE_COMMUNICATION content=CONTENT_TYPE_SPEECH flags=0x800 tags= bundle=null
volumeType=1, controlType=2, max=0, current=0
metadata: null
queueTitle=null, size=0
User Records:
Record for full_user=0
Volume key long-press listener: null
Volume key long-press listener package:
Media key listener: null
Media key listener package:
OnMediaKeyEventDispatchedListener: added 0 listener(s)
OnMediaKeyEventSessionChangedListener: added 0 listener(s)
Last MediaButtonReceiver: null
Media button session is null
Sessions Stack - have 0 sessions:
Audio playback (lastly played comes first)
uid=10163 packages=com.example.radioplayer
Media session config:
media_button_receiver_fgs_allowlist_duration_ms: [cur: 10000, def: 10000]
media_session_calback_fgs_allowlist_duration_ms: [cur: 10000, def: 10000]
media_session_callback_fgs_while_in_use_temp_allow_duration_ms: [cur: 10000, def: 10000]
It gives exactly same info when service is killed
@MrBzik any progress on this? Have you solved your problem?
@YuriPopiv Hi. Did not check my account for a while, sorry. No, I had to move on to other issues. And described solution with killing process is kind of working. Never failed me for a month of app testing.