美文网首页Android开发
Android开发暂停其他app的音频播放

Android开发暂停其他app的音频播放

作者: 你的益达233 | 来源:发表于2021-09-09 09:50 被阅读0次

    其实你是没办法控制其他app,只是把audio这个服务抢过来。具体原理还没搞清楚。先提供代码给你们,能用最好。

    public void stopOtherAppVoice(final Context context){
        this.mAudioManager = (AudioManager)context.getApplicationContext().getSystemService("audio");
        if (!this.isHeadphonesPlugged(this.mAudioManager)) {
            this._sensorManager = (SensorManager)context.getApplicationContext().getSystemService("sensor");
            if (this._sensorManager != null) {
                this._sensor = this._sensorManager.getDefaultSensor(8);
                this._sensorManager.registerListener(this, this._sensor, 3);
            }
        }
    
        this.muteAudioFocus(this.mAudioManager, true);
    }
    
    @TargetApi(8)
    private void muteAudioFocus(AudioManager audioManager, boolean bMute) {
        synchronized(this.mLock) {
            if (audioManager != null) {
                if (bMute) {
                    audioManager.requestAudioFocus(this.afChangeListener, 3, 2);
                } else {
                    audioManager.abandonAudioFocus(this.afChangeListener);
                    this.afChangeListener = null;
                }
    
            }
        }
    }
    

    关键代码就这些,要完整代码的,私信我。

    相关文章

      网友评论

        本文标题:Android开发暂停其他app的音频播放

        本文链接:https://www.haomeiwen.com/subject/fyriwltx.html