I'm trying to get the volume value of the Spotify Music Stream. I am able to get it throw STREAM_MUSIC when Spotify is playing music from the Android device or while the Android device is connected to a bluetooth speaker.
But when I'm streaming from the Android device to my Spotify App on the Smart TV/TV Streamer, Android is creating a new volume stream called: "Spotify" (as in the picture) How can I get this value?
Picture of Volume Streams on my Android device
Please help me understand how can I get the volume of this stream.. Thanks!
Actually, it is so difficult.
First, you have to use MediaSessionManager.getActiveSessions https://developer.android.com/reference/android/media/session/MediaSessionManager#getActiveSessions(android.content.ComponentName)
But it needs NotificationListenerService. Please refer to 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>
Request permission
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;
}
}
Main code
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();
}
}
or you can get it with callback
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();
}
});
}
}