如何处理来自 MediaSession 远程卷覆盖的更改?
我正在尝试实现远程音量控制。它已经可以使用硬件音量键控制音量,但是当我尝试移动MediaSession远程音量覆盖中的滑块时,不会调用回调。我也尝试了其他回调,如or,但它们根本没有被调用。VolumeProviderCompat.onAdjustVolume(..)
MediaSessionCompat.Callback.onMediaButtonEvent(..)
VolumeProviderCompat.onSetVolumeTo(..)
如果您不知道“MediaSession远程卷覆盖”是什么意思,这里有一个屏幕截图:
我创建了一个演示项目,您可以在此处下载:https://github.com/SaschaZ/VolumeProviderDemo。
以下是我的相关部分:DemoActivity
public class DemoActivity extends AppCompatActivity {
...
private Notification createNotification(@NonNull final DemoVolumeController demoVolumeController) {
Log.d(TAG, "createNotification()");
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSmallIcon(R.mipmap.ic_launcher);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (session != null) {
session.release();
}
session = new MediaSessionCompat(this, "demoMediaSession");
session.setPlaybackState(new PlaybackStateCompat.Builder()
.setState(PlaybackStateCompat.STATE_PLAYING, 1, 1.0f)
.build());
session.setPlaybackToRemote(createVolumeProvider(demoVolumeController));
session.setActive(true);
}
return builder.build();
}
private VolumeProviderCompat createVolumeProvider(@NonNull final DemoVolumeController demoVolumeController) {
// I don't use this callback directly, but I need to set it or my VolumeProvider will not work. (sounds
// strange but I tried it several times)
session.setCallback(new MediaSessionCompat.Callback() {
@Override
public boolean onMediaButtonEvent(final Intent mediaButtonEvent) {
Log.d(TAG, "onMediaButtonEvent() called with: " + "mediaButtonEvent = [" + mediaButtonEvent + "]");
return super.onMediaButtonEvent(mediaButtonEvent);
}
});
return new VolumeProviderCompat(VolumeProviderCompat.VOLUME_CONTROL_RELATIVE,
100,
demoVolumeController.getVolume()) {
@Override
public void onAdjustVolume(final int direction) {
final int volume = demoVolumeController.setVolumeRelative(direction);
showVolume(volume);
Log.d(TAG, "onAdjustVolume() called with: " + "direction = [" + direction + "] - " +
"new volume=" + volume);
// Nasty hack to get sync with the volume overlay of Android. setCurrentVolume does not work :(
session.setPlaybackToRemote(createVolumeProvider(demoVolumeController));
}
};
}
...
}
任何提示?提前感谢您!