Java Code Examples for android.media.AudioManager#abandonAudioFocus()

The following examples show how to use android.media.AudioManager#abandonAudioFocus() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IjkVideoView.java    From AndroidTvDemo with Apache License 2.0 6 votes vote down vote up
public void release(boolean cleartargetstate)
{
    if (mMediaPlayer != null)
    {
        mMediaPlayer.reset();
        mMediaPlayer.release();
        mMediaPlayer = null;
        // REMOVED: mPendingSubtitleTracks.clear();
        mCurrentState = STATE_IDLE;
        if (cleartargetstate)
        {
            mTargetState = STATE_IDLE;
        }
        AudioManager am = (AudioManager)mAppContext.getSystemService(Context.AUDIO_SERVICE);
        am.abandonAudioFocus(null);
    }
}
 
Example 2
Source File: Jzvd.java    From imsdk-android with MIT License 6 votes vote down vote up
/**
 * 多数表现为中断当前播放
 */
public void reset() {
    Log.i(TAG, "reset " + " [" + this.hashCode() + "] ");
    if (state == STATE_PLAYING || state == STATE_PAUSE) {
        long position = getCurrentPositionWhenPlaying();
        JZUtils.saveProgress(getContext(), jzDataSource.getCurrentUrl(), position);
    }
    cancelProgressTimer();
    dismissBrightnessDialog();
    dismissProgressDialog();
    dismissVolumeDialog();
    onStateNormal();
    textureViewContainer.removeAllViews();
    JZMediaInterface.SAVED_SURFACE = null;

    AudioManager mAudioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
    mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
    JZUtils.scanForActivity(getContext()).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    if (mediaInterface != null) mediaInterface.release();
}
 
Example 3
Source File: MediaSnippetsActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
public void onAudioFocusChange(int focusChange) {
  AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
  switch (focusChange) {
    case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK):
      // Lower the volume while ducking.
      mediaPlayer.setVolume(0.2f, 0.2f);
      break;
    case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT):
      mediaPlayer.pause();
      break;
    case (AudioManager.AUDIOFOCUS_LOSS):
      mediaPlayer.stop();
      am.abandonAudioFocus(this);
      break;
    case (AudioManager.AUDIOFOCUS_GAIN):
      // Return the volume to normal and resume if paused.
      mediaPlayer.setVolume(1f, 1f);
      mediaPlayer.start();
      break;
    default:
      break;
  }
}
 
Example 4
Source File: SignalAudioManager.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
public void stop(boolean playDisconnected) {
  AudioManager audioManager = AppUtil.INSTANCE.getAudioManager(context);

  incomingRinger.stop();
  outgoingRinger.stop();

  if (playDisconnected) {
    soundPool.play(disconnectedSoundId, 1.0f, 1.0f, 0, 0, 1.0f);
  }

  if (audioManager.isBluetoothScoOn()) {
    audioManager.setBluetoothScoOn(false);
    audioManager.stopBluetoothSco();
  }

  audioManager.setSpeakerphoneOn(false);
  audioManager.setMicrophoneMute(false);
  audioManager.setMode(AudioManager.MODE_NORMAL);
  audioManager.abandonAudioFocus(null);
}
 
Example 5
Source File: IjkVideoView.java    From ShareBox with Apache License 2.0 5 votes vote down vote up
public void stopPlayback() {
    if (mMediaPlayer != null) {
        mMediaPlayer.stop();
        mMediaPlayer.release();
        mMediaPlayer = null;
        mCurrentState = STATE_IDLE;
        mTargetState = STATE_IDLE;
        AudioManager am = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);
        am.abandonAudioFocus(null);
    }
}
 
Example 6
Source File: MediaPlayerListener.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@CalledByNative
public void releaseResources() {
    if (mContext != null) {
        // Unregister the wish for audio focus.
        AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        if (am != null) {
            am.abandonAudioFocus(this);
        }
    }
}
 
Example 7
Source File: IjkVideoView.java    From LivePlayback with Apache License 2.0 5 votes vote down vote up
public void stopPlayback() {
    if (mMediaPlayer != null) {
        mMediaPlayer.stop();
        mMediaPlayer.release();
        mMediaPlayer = null;
        if (mHudViewHolder != null)
            mHudViewHolder.setMediaPlayer(null);
        mCurrentState = STATE_IDLE;
        mTargetState = STATE_IDLE;
        AudioManager am = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);
        am.abandonAudioFocus(null);
    }
}
 
Example 8
Source File: IjkVideoView.java    From MD with Apache License 2.0 5 votes vote down vote up
public void stopPlayback() {
    if (mMediaPlayer != null) {
        mMediaPlayer.stop();
        mMediaPlayer.release();
        mMediaPlayer = null;
        if (mHudViewHolder != null)
            mHudViewHolder.setMediaPlayer(null);
        mCurrentState = STATE_IDLE;
        mTargetState = STATE_IDLE;
        AudioManager am = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);
        am.abandonAudioFocus(null);
    }
}
 
Example 9
Source File: MediaPlayerView.java    From HeroVideo-master with Apache License 2.0 5 votes vote down vote up
public void release(boolean cleartargetstate) {
    if (mMediaPlayer != null) {
        mMediaPlayer.reset();
        mMediaPlayer.release();
        mMediaPlayer = null;
        // REMOVED: mPendingSubtitleTracks.clear();
        mCurrentState = STATE_IDLE;
        if (cleartargetstate) {
            mTargetState = STATE_IDLE;
        }
        AudioManager am = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);
        am.abandonAudioFocus(null);
    }
}
 
Example 10
Source File: BaseVideoView.java    From PlayerBase with Apache License 2.0 5 votes vote down vote up
private void releaseAudioFocus(){
    PLog.d(TAG,"<<releaseAudioFocus>>");
    AudioManager am = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
    if(am!=null){
        am.abandonAudioFocus(null);
    }
}
 
Example 11
Source File: LivePlayerHolder.java    From likequanmintv with Apache License 2.0 5 votes vote down vote up
public void release() {
    if (mMediaPlayer != null) {
        mMediaPlayer.stop();
        mMediaPlayer.release();
        mMediaPlayer = null;
    }
    if (mSurfaceView.getHolder()!=null){
        mSurfaceView.getHolder().removeCallback(mCallback);
    }

    AudioManager audioManager = (AudioManager) APP.getContext().getSystemService(Context.AUDIO_SERVICE);
    audioManager.abandonAudioFocus(null);

}
 
Example 12
Source File: TextureVideoView.java    From texturevideoview with Apache License 2.0 5 votes vote down vote up
public void stopPlayback() {
    if (mMediaPlayer != null) {
        mMediaPlayer.stop();
        mMediaPlayer.release();
        mMediaPlayer = null;
        mCurrentState = STATE_IDLE;
        mTargetState  = STATE_IDLE;
        if (mShouldRequestAudioFocus) {
            AudioManager am = (AudioManager) getContext().getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
            am.abandonAudioFocus(null);
        }
    }
    clearSurface();
}
 
Example 13
Source File: ParsingPlayerProxy.java    From ParsingPlayer with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Release current used player
 */
private void releasePlayer() {
    if (mPlayer != null) {
        mPlayer.reset();
        mPlayer.release();
        mPlayer = null;
        mCurrentState = STATE_IDLE;
        AudioManager am = (AudioManager) mContextRef.get().getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
        am.abandonAudioFocus(null);
    }
}
 
Example 14
Source File: AudioManagerUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 放弃音频焦点, 使上一个焦点所有者 ( 如果有 ) 接收焦点
 * @param listener 焦点监听事件
 * @return {@code true} success, {@code false} fail
 */
public static boolean abandonAudioFocus(final AudioManager.OnAudioFocusChangeListener listener) {
    AudioManager audioManager = AppUtils.getAudioManager();
    if (audioManager != null) {
        try {
            audioManager.abandonAudioFocus(listener);
            return true;
        } catch (Exception e) {
            LogPrintUtils.eTag(TAG, e, "abandonAudioFocus");
        }
    }
    return false;
}
 
Example 15
Source File: AssetVideoView.java    From ResearchStack with Apache License 2.0 5 votes vote down vote up
private void release(boolean cleartargetstate) {
    if (mMediaPlayer != null) {
        mMediaPlayer.reset();
        mMediaPlayer.release();
        mMediaPlayer = null;
        mCurrentState = STATE_IDLE;
        if (cleartargetstate) {
            mTargetState = STATE_IDLE;
        }
        AudioManager am = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
        am.abandonAudioFocus(null);
    }
}
 
Example 16
Source File: IjkVideoView.java    From MD with Apache License 2.0 5 votes vote down vote up
public void release(boolean cleartargetstate) {
    if (mMediaPlayer != null) {
        mMediaPlayer.reset();
        mMediaPlayer.release();
        mMediaPlayer = null;
        // REMOVED: mPendingSubtitleTracks.clear();
        mCurrentState = STATE_IDLE;
        if (cleartargetstate) {
            mTargetState = STATE_IDLE;
        }
        AudioManager am = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);
        am.abandonAudioFocus(null);
    }
}
 
Example 17
Source File: MainService.java    From android-play-games-in-motion with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate() {
    // The service is being created.
    Utils.logDebug(TAG, "onCreate");
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_1);
    intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_2);
    intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_3);
    registerReceiver(mReceiver, intentFilter);

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    // Determines the behavior for handling Audio Focus surrender.
    mAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT
                    || focusChange == AudioManager.AUDIOFOCUS_LOSS) {

                if (mTextToSpeech.isSpeaking()) {
                    mTextToSpeech.setOnUtteranceProgressListener(null);
                    mTextToSpeech.stop();
                }

                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.stop();
                }

                // Abandon Audio Focus, if it's requested elsewhere.
                mAudioManager.abandonAudioFocus(mAudioFocusChangeListener);

                // Restart the current moment if AudioFocus was lost. Since AudioFocus is only
                // requested away from this application if this application was using it,
                // only Moments that play sound will restart in this way.
                if (mMission != null) {
                    mMission.restartMoment();
                }
            }
        }
    };

    // Asynchronously prepares the TextToSpeech.
    mTextToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                // Check if language is available.
                switch (mTextToSpeech.isLanguageAvailable(DEFAULT_TEXT_TO_SPEECH_LOCALE)) {
                    case TextToSpeech.LANG_AVAILABLE:
                    case TextToSpeech.LANG_COUNTRY_AVAILABLE:
                    case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
                        Utils.logDebug(TAG, "TTS locale supported.");
                        mTextToSpeech.setLanguage(DEFAULT_TEXT_TO_SPEECH_LOCALE);
                        mIsTextToSpeechReady = true;
                        break;
                    case TextToSpeech.LANG_MISSING_DATA:
                        Utils.logDebug(TAG, "TTS missing data, ask for install.");
                        Intent installIntent = new Intent();
                        installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                        startActivity(installIntent);
                        break;
                    default:
                        Utils.logDebug(TAG, "TTS local not supported.");
                        break;
                }
            }
        }
    });

    mMediaPlayer = new MediaPlayer();
}
 
Example 18
Source File: PlayManager.java    From BeMusic with Apache License 2.0 4 votes vote down vote up
private int releaseAudioFocus () {
    AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
    Log.v(TAG, "releaseAudioFocus by ");
    return audioManager.abandonAudioFocus(mAfListener);
}
 
Example 19
Source File: VoIPBaseService.java    From Telegram-FOSS with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onDestroy() {
	if (BuildVars.LOGS_ENABLED) {
		FileLog.d("=============== VoIPService STOPPING ===============");
	}
	stopForeground(true);
	stopRinging();
	NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.appDidLogout);
	SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
	Sensor proximity = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
	if (proximity != null) {
		sm.unregisterListener(this);
	}
	if (proximityWakelock != null && proximityWakelock.isHeld()) {
		proximityWakelock.release();
	}
	unregisterReceiver(receiver);
	if(timeoutRunnable!=null){
		AndroidUtilities.cancelRunOnUIThread(timeoutRunnable);
		timeoutRunnable=null;
	}
	super.onDestroy();
	sharedInstance = null;
	AndroidUtilities.runOnUIThread(new Runnable(){
		@Override
		public void run(){
			NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didEndCall);
		}
	});
	if (tgVoip != null) {
		updateTrafficStats();
		StatsController.getInstance(currentAccount).incrementTotalCallsTime(getStatsNetworkType(), (int) (getCallDuration() / 1000) % 5);
		onTgVoipPreStop();
		onTgVoipStop(tgVoip.stop());
		prevTrafficStats = null;
		callStartTime = 0;
		tgVoip = null;
	}
	cpuWakelock.release();
	AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
	if(!USE_CONNECTION_SERVICE){
		if(isBtHeadsetConnected && !playingSound){
			am.stopBluetoothSco();
			am.setBluetoothScoOn(false);
			am.setSpeakerphoneOn(false);
		}
		try{
			am.setMode(AudioManager.MODE_NORMAL);
		}catch(SecurityException x){
			if(BuildVars.LOGS_ENABLED){
				FileLog.e("Error setting audio more to normal", x);
			}
		}
		am.abandonAudioFocus(this);
	}
	am.unregisterMediaButtonEventReceiver(new ComponentName(this, VoIPMediaButtonReceiver.class));
	if (haveAudioFocus)
		am.abandonAudioFocus(this);

	if (!playingSound)
		soundPool.release();

	if(USE_CONNECTION_SERVICE){
		if(!didDeleteConnectionServiceContact)
			ContactsController.getInstance(currentAccount).deleteConnectionServiceContact();
		if(systemCallConnection!=null && !playingSound){
			systemCallConnection.destroy();
		}
	}

	ConnectionsManager.getInstance(currentAccount).setAppPaused(true, false);
	VoIPHelper.lastCallTime=System.currentTimeMillis();
}
 
Example 20
Source File: VoIPBaseService.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onDestroy() {
	if (BuildVars.LOGS_ENABLED) {
		FileLog.d("=============== VoIPService STOPPING ===============");
	}
	stopForeground(true);
	stopRinging();
	NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.appDidLogout);
	SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
	Sensor proximity = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
	if (proximity != null) {
		sm.unregisterListener(this);
	}
	if (proximityWakelock != null && proximityWakelock.isHeld()) {
		proximityWakelock.release();
	}
	unregisterReceiver(receiver);
	if(timeoutRunnable!=null){
		AndroidUtilities.cancelRunOnUIThread(timeoutRunnable);
		timeoutRunnable=null;
	}
	super.onDestroy();
	sharedInstance = null;
	AndroidUtilities.runOnUIThread(new Runnable(){
		@Override
		public void run(){
			NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didEndedCall);
		}
	});
	if (controller != null && controllerStarted) {
		lastKnownDuration = controller.getCallDuration();
		updateStats();
		StatsController.getInstance(currentAccount).incrementTotalCallsTime(getStatsNetworkType(), (int) (lastKnownDuration / 1000) % 5);
		onControllerPreRelease();
		controller.release();
		controller = null;
	}
	cpuWakelock.release();
	AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
	if(!USE_CONNECTION_SERVICE){
		if(isBtHeadsetConnected && !playingSound){
			am.stopBluetoothSco();
			am.setSpeakerphoneOn(false);
		}
		try{
			am.setMode(AudioManager.MODE_NORMAL);
		}catch(SecurityException x){
			if(BuildVars.LOGS_ENABLED){
				FileLog.e("Error setting audio more to normal", x);
			}
		}
		am.abandonAudioFocus(this);
	}
	am.unregisterMediaButtonEventReceiver(new ComponentName(this, VoIPMediaButtonReceiver.class));
	if (haveAudioFocus)
		am.abandonAudioFocus(this);

	if (!playingSound)
		soundPool.release();

	if(USE_CONNECTION_SERVICE){
		if(systemCallConnection!=null && !playingSound){
			systemCallConnection.destroy();
		}
	}

	ConnectionsManager.getInstance(currentAccount).setAppPaused(true, false);
	VoIPHelper.lastCallTime=System.currentTimeMillis();
}