Android禁用音频系统弹出

时间:2017-09-19 14:24:52

标签: android audio

我尝试在播放视频时与Snapchat / instagram音频控制相同。

我在API21 +

如何禁用音频系统弹出窗口?并且仍然拦截命令

如果您通过声音触摸以外的方式控制声音,我可以这样做但不起作用

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC) + 1, 0);
                return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC) - 1, 0);
                return true;
        }
    }
    return super.dispatchKeyEvent(event);
}

我试试这个,但它不能正常工作

mAudioManager.requestAudioFocus(new AudioManager.OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int i) {
            Log.d(TAG, "onAudioFocusChange: " + i);
            MediaSessionCompat sessionCompat = new MediaSessionCompat(getApplicationContext(), "TAG");
            sessionCompat.setCallback(new MediaSessionCompat.Callback() {
                @Override
                public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
                    Log.d(TAG, "onMediaButtonEvent: " + mediaButtonEvent);
                    return super.onMediaButtonEvent(mediaButtonEvent);
                }
            });
            sessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
            sessionCompat.setPlaybackToRemote(new VolumeProviderCompat(VolumeProviderCompat.VOLUME_CONTROL_FIXED, 15, 5) {
                @Override
                public void onSetVolumeTo(int volume) {
                    Log.d(TAG, "onSetVolumeTo: ");
                    super.onSetVolumeTo(volume);
                }

                @Override
                public void onAdjustVolume(int direction) {
                    super.onAdjustVolume(direction);
                }

                @Override
                public void setCallback(Callback callback) {
                    super.setCallback(callback);
                }
            });
            sessionCompat.setActive(true);
        }
    }, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

0 个答案:

没有答案