Example usage for android.media AudioManager abandonAudioFocus

List of usage examples for android.media AudioManager abandonAudioFocus

Introduction

In this page you can find the example usage for android.media AudioManager abandonAudioFocus.

Prototype

public int abandonAudioFocus(OnAudioFocusChangeListener l) 

Source Link

Document

Abandon audio focus.

Usage

From source file:org.videolan.vlc.audio.AudioService.java

@TargetApi(Build.VERSION_CODES.FROYO)
private void changeAudioFocus(boolean gain) {
    if (!LibVlcUtil.isFroyoOrLater()) // NOP if not supported
        return;/*from w  w  w.  j a v  a  2s.c o  m*/

    if (audioFocusListener == null) {
        audioFocusListener = new OnAudioFocusChangeListener() {
            @Override
            public void onAudioFocusChange(int focusChange) {
                LibVLC libVLC = LibVLC.getExistingInstance();
                switch (focusChange) {
                case AudioManager.AUDIOFOCUS_LOSS:
                    if (libVLC.isPlaying())
                        libVLC.pause();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    /*
                     * Lower the volume to 36% to "duck" when an alert or something
                     * needs to be played.
                     */
                    libVLC.setVolume(36);
                    break;
                case AudioManager.AUDIOFOCUS_GAIN:
                case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT:
                case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
                    libVLC.setVolume(100);
                    break;
                }
            }
        };
    }

    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (gain)
        am.requestAudioFocus(audioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    else
        am.abandonAudioFocus(audioFocusListener);

}

From source file:com.hotstar.player.adplayer.player.PlayerFragment.java

private void abandonAudioFocus() {
    AudioManager am = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
    am.abandonAudioFocus(null);

    AdVideoApplication.logger.i(LOG_TAG + "#abandonAudioFocus()", "Abandoned audio focus.");
}

From source file:com.fastbootmobile.encore.service.PlaybackService.java

/**
 * Release the audio focus and unregisters the media controls
 *//*from  w  w  w  .j a  va  2s.  c  o m*/
private synchronized void abandonAudioFocus() {
    if (mHasAudioFocus) {
        // Release the audio focus
        final AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        am.abandonAudioFocus(this);
        unregisterReceiver(mAudioNoisyReceiver);

        // Release our CPU wakelock
        mWakeLock.release();

        // Notify the remote metadata that we're getting down
        mRemoteMetadata.setActive(false);

        mHasAudioFocus = false;
    }
}

From source file:org.videolan.vlc.PlaybackService.java

@TargetApi(Build.VERSION_CODES.FROYO)
private void changeAudioFocus(boolean gain) {
    if (!AndroidUtil.isFroyoOrLater()) // NOP if not supported
        return;//from   w w w.  j a va  2 s .c o  m

    if (audioFocusListener == null) {
        audioFocusListener = new OnAudioFocusChangeListener() {
            @Override
            public void onAudioFocusChange(int focusChange) {
                if (!hasCurrentMedia())
                    return;
                switch (focusChange) {
                case AudioManager.AUDIOFOCUS_LOSS:
                    if (MediaPlayer().isPlaying())
                        MediaPlayer().pause();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    /*
                     * Lower the volume to 36% to "duck" when an alert or something
                     * needs to be played.
                     */
                    MediaPlayer().setVolume(36);
                    break;
                case AudioManager.AUDIOFOCUS_GAIN:
                case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT:
                case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
                    MediaPlayer().setVolume(100);
                    break;
                }
            }
        };
    }

    AudioManager am = (AudioManager) VLCApplication.getAppContext().getSystemService(AUDIO_SERVICE);
    if (gain)
        am.requestAudioFocus(audioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    else
        am.abandonAudioFocus(audioFocusListener);

}

From source file:com.dzt.musicplay.player.AudioService.java

@TargetApi(Build.VERSION_CODES.FROYO)
private void changeAudioFocus(boolean gain) {
    if (!LibVlcUtil.isFroyoOrLater()) // NOP if not supported
        return;//from w ww  .  j  a v a  2  s . c  o  m

    if (audioFocusListener == null) {
        audioFocusListener = new OnAudioFocusChangeListener() {
            @Override
            public void onAudioFocusChange(int focusChange) {
                LibVLC libVLC = LibVLC.getExistingInstance();
                switch (focusChange) {
                case AudioManager.AUDIOFOCUS_LOSS:
                    if (libVLC.isPlaying())
                        libVLC.pause();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    /*
                     * Lower the volume to 36% to "duck" when an alert or
                     * something needs to be played.
                     */
                    libVLC.setVolume(36);
                    break;
                case AudioManager.AUDIOFOCUS_GAIN:
                case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT:
                case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
                    libVLC.setVolume(100);
                    break;
                }
            }
        };
    }

    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (gain)
        am.requestAudioFocus(audioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    else
        am.abandonAudioFocus(audioFocusListener);

}

From source file:com.ferdi2005.secondgram.voip.VoIPService.java

@Override
public void onDestroy() {
    FileLog.d("=============== VoIPService STOPPING ===============");
    stopForeground(true);//  w  w  w  . ja  v  a2  s.  co  m
    stopRinging();
    NotificationCenter.getInstance().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.getInstance().postNotificationName(NotificationCenter.didEndedCall);
        }
    });
    if (controller != null && controllerStarted) {
        lastKnownDuration = controller.getCallDuration();
        updateStats();
        StatsController.getInstance().incrementTotalCallsTime(getStatsNetworkType(),
                (int) (lastKnownDuration / 1000) % 5);
        if (needSendDebugLog) {
            String debugLog = controller.getDebugLog();
            TLRPC.TL_phone_saveCallDebug req = new TLRPC.TL_phone_saveCallDebug();
            req.debug = new TLRPC.TL_dataJSON();
            req.debug.data = debugLog;
            req.peer = new TLRPC.TL_inputPhoneCall();
            req.peer.access_hash = call.access_hash;
            req.peer.id = call.id;
            ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
                @Override
                public void run(TLObject response, TLRPC.TL_error error) {
                    FileLog.d("Sent debug logs, response=" + response);
                }
            });
        }
        controller.release();
        controller = null;
    }
    cpuWakelock.release();
    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (isBtHeadsetConnected && !playingSound)
        am.stopBluetoothSco();
    am.setMode(AudioManager.MODE_NORMAL);
    am.unregisterMediaButtonEventReceiver(new ComponentName(this, VoIPMediaButtonReceiver.class));
    if (haveAudioFocus)
        am.abandonAudioFocus(this);

    if (!playingSound)
        soundPool.release();

    ConnectionsManager.getInstance().setAppPaused(true, false);
}

From source file:dk.dr.radio.afspilning.Afspiller.java

    /**
 * Responding to the loss of audio focus
 *//* ww w  . j  a v a  2s.  com*/
@SuppressLint("NewApi")
private OnAudioFocusChangeListener getOnAudioFocusChangeListener() {
  if (onAudioFocusChangeListener == null)
    onAudioFocusChangeListener = new OnAudioFocusChangeListener() {

      //private int lydstyreFrDuck = -1;

      @TargetApi(Build.VERSION_CODES.FROYO)
      public void onAudioFocusChange(int focusChange) {
        Log.d("onAudioFocusChange " + focusChange);
        AudioManager am = (AudioManager) App.instans.getSystemService(Context.AUDIO_SERVICE);

        switch (focusChange) {
          // Kommer ved f.eks. en SMS eller taleinstruktion i Google Maps
          case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK):
            Log.d("JPER duck");
            if (afspillerstatus != Status.STOPPET) {
              // Vi 'dukker' lyden mens den vigtigere lyd hres
              // St lydstyrken ned til en 1/3-del
              //lydstyreFrDuck = am.getStreamVolume(AudioManager.STREAM_MUSIC);
              //am.setStreamVolume(AudioManager.STREAM_MUSIC, (lydstyreFrDuck + 2) / 3, 0);
              mediaPlayer.setVolume(0.1f, 0.1f); // logaritmisk skala - 0.1 svarer til 1/3-del
            }
            break;

          // Dette sker ved f.eks. opkald
          case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT):
            Log.d("JPER pause");
            if (afspillerstatus != Status.STOPPET) {
              pauseAfspilning(); // stter afspilningPPause=false
              if (afspillerlyde) afspillerlyd.stop.start();
              afspilningPPause = true;
            }
            break;

          // Dette sker hvis en anden app med lyd startes, f.eks. et spil
          case (AudioManager.AUDIOFOCUS_LOSS):
            Log.d("JPER stop");
            stopAfspilning();
            am.abandonAudioFocus(this);
            break;

          // Dette sker nr opkaldet er slut og ved f.eks. opkald
          case (AudioManager.AUDIOFOCUS_GAIN):
            Log.d("JPER Gain");
            if (afspillerstatus == Status.STOPPET) {
              if (afspilningPPause) startAfspilningIntern();
            } else {
              // Genskab lydstyrke fr den blev dukket
              mediaPlayer.setVolume(1f, 1f);
              //if (lydstyreFrDuck > 0) {
              //  am.setStreamVolume(AudioManager.STREAM_MUSIC, lydstyreFrDuck, 0);
              //}
              // Genstart ikke afspilning, der spilles allerede!
              //startAfspilningIntern();
            }
        }
      }
    };
  return (OnAudioFocusChangeListener) onAudioFocusChangeListener;
}

From source file:dk.nota.lyt.libvlc.PlaybackService.java

private void changeAudioFocus(boolean acquire) {
    final AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (am == null)
        return;/*  www  . j a v  a  2  s  . c  o  m*/

    if (acquire) {
        if (!mHasAudioFocus) {
            final int result = am.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
                    AudioManager.AUDIOFOCUS_GAIN);
            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                am.setParameters("bgm_state=true");
                mHasAudioFocus = true;
            }
        }
    } else {
        if (mHasAudioFocus) {
            final int result = am.abandonAudioFocus(mAudioFocusListener);
            am.setParameters("bgm_state=false");
            mHasAudioFocus = false;
        }
    }
}

From source file:github.daneren2005.dsub.util.Util.java

@TargetApi(8)
public static void requestAudioFocus(final Context context) {
    if (Build.VERSION.SDK_INT >= 8 && !hasFocus) {
        final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        hasFocus = true;/*from w  w w  .jav a  2  s. c  om*/
        audioManager.requestAudioFocus(new OnAudioFocusChangeListener() {
            public void onAudioFocusChange(int focusChange) {
                DownloadServiceImpl downloadService = (DownloadServiceImpl) context;
                if ((focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT
                        || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)
                        && !downloadService.isJukeboxEnabled()) {
                    if (downloadService.getPlayerState() == PlayerState.STARTED) {
                        SharedPreferences prefs = getPreferences(context);
                        int lossPref = Integer
                                .parseInt(prefs.getString(Constants.PREFERENCES_KEY_TEMP_LOSS, "1"));
                        if (lossPref == 2 || (lossPref == 1
                                && focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)) {
                            lowerFocus = true;
                            downloadService.setVolume(0.1f);
                        } else if (lossPref == 0
                                || (lossPref == 1 && focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)) {
                            pauseFocus = true;
                            downloadService.pause();
                        }
                    }
                } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                    if (pauseFocus) {
                        pauseFocus = false;
                        downloadService.start();
                    } else if (lowerFocus) {
                        lowerFocus = false;
                        downloadService.setVolume(1.0f);
                    }
                } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS && !downloadService.isJukeboxEnabled()) {
                    hasFocus = false;
                    downloadService.pause();
                    audioManager.abandonAudioFocus(this);
                }
            }
        }, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    }
}

From source file:com.thejoshwa.ultrasonic.androidapp.util.Util.java

public static void requestAudioFocus(final Context context) {
    if (!hasFocus) {
        final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        hasFocus = true;/*from   w  w  w.  jav a  2  s.c o m*/
        audioManager.requestAudioFocus(new OnAudioFocusChangeListener() {
            public void onAudioFocusChange(int focusChange) {
                DownloadServiceImpl downloadService = (DownloadServiceImpl) context;
                if ((focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT
                        || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)
                        && !downloadService.isJukeboxEnabled()) {
                    if (downloadService.getPlayerState() == PlayerState.STARTED) {
                        SharedPreferences prefs = getPreferences(context);
                        int lossPref = Integer
                                .parseInt(prefs.getString(Constants.PREFERENCES_KEY_TEMP_LOSS, "1"));
                        if (lossPref == 2 || (lossPref == 1
                                && focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)) {
                            lowerFocus = true;
                            downloadService.setVolume(0.1f);
                        } else if (lossPref == 0
                                || (lossPref == 1 && focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)) {
                            pauseFocus = true;
                            downloadService.pause();
                        }
                    }
                } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                    if (pauseFocus) {
                        pauseFocus = false;
                        downloadService.start();
                    } else if (lowerFocus) {
                        lowerFocus = false;
                        downloadService.setVolume(1.0f);
                    }
                } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS && !downloadService.isJukeboxEnabled()) {
                    hasFocus = false;
                    downloadService.pause();
                    audioManager.abandonAudioFocus(this);
                }
            }
        }, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    }
}