其实,太难了。
首先,您必须使用 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();
}
});
}
}