1 /* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.settingslib.media.session 18 19 import android.media.session.MediaController 20 import android.media.session.MediaSession 21 import android.media.session.MediaSessionManager 22 import android.os.UserHandle 23 import androidx.concurrent.futures.DirectExecutor 24 import kotlinx.coroutines.channels.Channel 25 import kotlinx.coroutines.channels.awaitClose 26 import kotlinx.coroutines.flow.Flow 27 import kotlinx.coroutines.flow.buffer 28 import kotlinx.coroutines.flow.callbackFlow 29 import kotlinx.coroutines.launch 30 31 /** [Flow] for [MediaSessionManager.OnActiveSessionsChangedListener]. */ 32 val MediaSessionManager.activeMediaChanges: Flow<List<MediaController>?> 33 get() = <lambda>null34 callbackFlow { 35 val listener = 36 MediaSessionManager.OnActiveSessionsChangedListener { launch { send(it) } } 37 addOnActiveSessionsChangedListener( 38 null, 39 UserHandle.of(UserHandle.myUserId()), 40 DirectExecutor.INSTANCE, 41 listener, 42 ) 43 awaitClose { removeOnActiveSessionsChangedListener(listener) } 44 } 45 .buffer(capacity = Channel.CONFLATED) 46 47 /** [Flow] for [MediaSessionManager.RemoteSessionCallback]. */ 48 val MediaSessionManager.defaultRemoteSessionChanged: Flow<MediaSession.Token?> 49 get() = <lambda>null50 callbackFlow { 51 val callback = 52 object : MediaSessionManager.RemoteSessionCallback { 53 override fun onVolumeChanged(sessionToken: MediaSession.Token, flags: Int) = 54 Unit 55 56 override fun onDefaultRemoteSessionChanged( 57 sessionToken: MediaSession.Token? 58 ) { 59 launch { send(sessionToken) } 60 } 61 } 62 registerRemoteSessionCallback(DirectExecutor.INSTANCE, callback) 63 awaitClose { unregisterRemoteSessionCallback(callback) } 64 } 65 .buffer(capacity = Channel.CONFLATED) 66