获取 Spotify 流媒体音量 | Android(科特林)

Get Spotify Stream Volume | Android (Kotlin)

我正在尝试获取 Spotify 音乐流的音量值。 当 Spotify 正在从 Android 设备播放音乐时或当 Android 设备连接到蓝牙扬声器时,我能够让它抛出 STREAM_MUSIC。

但是当我从 Android 设备流式传输到 Smart TV/TV Streamer 上的 Spotify 应用程序时,Android 正在创建一个名为:“Spotify”(如图) 我怎样才能得到这个值?

Picture of Volume Streams on my Android device

请帮助我了解如何获取此流的音量.. 谢谢!

其实好难

首先,你必须使用MediaSessionManager.getActiveSessions https://developer.android.com/reference/android/media/session/MediaSessionManager#getActiveSessions(android.content.ComponentName)

但是需要NotificationListenerService。 请参阅 https://developer.android.com/reference/android/service/notification/NotificationListenerService https://github.com/codechacha/NotificationListener

MyNotificationService.java

public class MyNotificationService extends NotificationListenerService {
    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        super.onNotificationRemoved(sbn);
    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        super.onNotificationPosted(sbn);
    }
}

AndroidManifest.xml

    <service
        android:name=".MyNotificationService"
        android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
        <intent-filter>
            <action android:name="android.service.notification.NotificationListenerService" />
        </intent-filter>
        <meta-data
            android:name="android.service.notification.default_filter_types"
            android:value="1,2">
        </meta-data>
    </service>

请求许可

if (!permissionGrantred()) {
    Intent intent = new Intent(
            "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
    startActivity(intent);
}


private boolean permissionGrantred() {
    Set<String> sets = NotificationManagerCompat.getEnabledListenerPackages(this);
    if (sets != null && sets.contains(getPackageName())) {
        return true;
    } else {
        return false;
    }
}

主要代码

MediaSessionManager msm = (MediaSessionManager)getSystemService(Context.MEDIA_SESSION_SERVICE);
ComponentName cn = new ComponentName(this, MyNotificationService.class);
List<MediaController> list = msm.getActiveSessions(cn);
for (MediaController mc : list) {
    if (mc.getPackageName().equals("com.spotify.music")) {
        int spotifyVolume = mc.getPlaybackInfo().getCurrentVolume();
    }
}

或者回调获取

for (MediaController mc : list) {
    if (mc.getPackageName().equals("com.spotify.music")) {
        mc.registerCallback(new MediaController.Callback() {
            @Override
            public void onAudioInfoChanged(MediaController.PlaybackInfo info) {
                int spotifyVolume = info.getCurrentVolume();
            }
        });
    }
}