Example usage for android.media AudioManager AUDIOFOCUS_LOSS

List of usage examples for android.media AudioManager AUDIOFOCUS_LOSS

Introduction

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

Prototype

int AUDIOFOCUS_LOSS

To view the source code for android.media AudioManager AUDIOFOCUS_LOSS.

Click Source Link

Document

Used to indicate a loss of audio focus of unknown duration.

Usage

From source file:com.sourceauditor.sahomemonitor.MainActivity.java

@Override
public void onAudioFocusChange(int focusChange) {
    switch (focusChange) {
    case AudioManager.AUDIOFOCUS_GAIN:
        if (paused()) {
            play();/*from w ww  .  j a v  a  2  s  .c o m*/
        } else {
            audioPlayer.setVolume(1.0f, 1.0f);
        }
        break;

    case AudioManager.AUDIOFOCUS_LOSS:
        // Lost focus for an unbounded amount of time: pause playback
        pause();
        break;

    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
        pause();
        break;

    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
        // Lost focus for a short time, but it's ok to keep playing
        // at an attenuated level
        if (!paused()) {
            audioPlayer.setVolume(0.1f, 0.1f);

        }
        break;
    }
}

From source file:leoisasmendi.android.com.suricatepodcast.services.MediaPlayerService.java

@Override
public void onAudioFocusChange(int focusState) {
    //Invoked when the audio focus of the system is updated.
    switch (focusState) {
    case AudioManager.AUDIOFOCUS_GAIN:
        // resume playback
        if (mediaPlayer == null)
            initMediaPlayer();//from  ww  w .  j  a v  a  2s .  c  o m
        else if (!mediaPlayer.isPlaying())
            mediaPlayer.start();
        mediaPlayer.setVolume(1.0f, 1.0f);
        break;
    case AudioManager.AUDIOFOCUS_LOSS:
        // Lost focus for an unbounded amount of time: stop playback and release media player
        if (mediaPlayer.isPlaying())
            mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
        break;
    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
        // Lost focus for a short time, but we have to stop
        // playback. We don't release the media player because playback
        // is likely to resume
        if (mediaPlayer.isPlaying())
            mediaPlayer.pause();
        break;
    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
        // Lost focus for a short time, but it's ok to keep playing
        // at an attenuated level
        if (mediaPlayer.isPlaying())
            mediaPlayer.setVolume(0.1f, 0.1f);
        break;
    }
}

From source file:com.shinymayhem.radiopresets.ServiceRadioPlayer.java

@Override
public void onAudioFocusChange(int focusChange) {
    if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
        mAudioFocused = false;/*from w  w  w.j av a 2  s  . com*/
        if (LOCAL_LOGD)
            log("AUDIOFOCUS_LOSS_TRANSIENT", "d");
        // Pause playback
        pause();
    } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
        mAudioFocused = true;
        if (LOCAL_LOGD)
            log("AUDIOFOCUS_GAIN", "d");
        // Resume playback or unduck
        if (shouldResumeOnAudioFocus()) {
            if (mCurrentPlayerState.equals(STATE_PAUSED)) {
                resume();
            } else {
                //find out which states this is run into from. change shouldResumeOnAudioFocus() accordingly (only resume when paused?)
                if (LOCAL_LOGD)
                    log("Focus gained,  but playback not resumed", "d"); //investigate
            }
        } else {
            if (LOCAL_LOGD)
                log("Focused gained but playback should not try to resume", "d");
            if (mPreset == 0) {

            }

        }
        unduck();

    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {

        if (LOCAL_LOGD)
            log("AUDIOFOCUS_LOSS", "d");
        if (mMediaButtonEventReceiverRegistered) {
            if (LOCAL_LOGV)
                log("unregister button receiver", "v");
            mAudioManager.unregisterMediaButtonEventReceiver(
                    new ComponentName(getPackageName(), ReceiverRemoteControl.class.getName()));
            mMediaButtonEventReceiverRegistered = false;
        } else {
            if (LOCAL_LOGV)
                log("button receiver already unregistered", "v");
        }
        //this.abandonAudioFocus(); //already done in stop()->pause()
        // Stop playback
        stop();

    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
        // Lower the volume
        if (LOCAL_LOGV)
            log("AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK", "v");
        duck();
    }

}

From source file:com.wojtechnology.sunami.TheBrain.java

private void registerAudio() {
    if (mHasAudioFocus || !mIsInit) {
        return;/*w  w w. j  a va2s  .  c o m*/
    }
    mHasAudioFocus = true;

    // Add audio focus change listener
    mAFChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                pausePlayback();
                setUI(false);
            } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                // Does nothing cause made me play music at work
            } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                pausePlayback();
                unregisterAudio();
                setUI(false);
            }
        }
    };

    mAudioManager.requestAudioFocus(mAFChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    // Add headphone out listener
    registerReceiver(mNoisyAudioStreamReceiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));

    // Add notification and transport controls
    ComponentName eventReceiver = new ComponentName(getPackageName(),
            RemoteControlEventReceiver.class.getName());
    mSession = new MediaSessionCompat(this, "FireSession", eventReceiver, null);
    mSession.setFlags(
            MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS | MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
    mSession.setPlaybackToLocal(AudioManager.STREAM_MUSIC);
    mSession.setMetadata(new MediaMetadataCompat.Builder().putString(MediaMetadataCompat.METADATA_KEY_TITLE, "")
            .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, "")
            .putLong(MediaMetadata.METADATA_KEY_DURATION, -1).build());

    mSession.setCallback(new MediaSessionCompat.Callback() {

        @Override
        public void onSeekTo(long pos) {
            super.onSeekTo(pos);
            setProgress((int) pos, isPlaying());
        }
    });
    mSession.setActive(true);
}

From source file:com.android.tv.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    if (DEBUG)/*from w ww.  j  a va 2s .  c  om*/
        Log.d(TAG, "onCreate()");
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M && !PermissionUtils.hasAccessAllEpg(this)) {
        Toast.makeText(this, R.string.msg_not_supported_device, Toast.LENGTH_LONG).show();
        finish();
        return;
    }
    boolean skipToShowOnboarding = getIntent().getAction() == Intent.ACTION_VIEW
            && TvContract.isChannelUriForPassthroughInput(getIntent().getData());
    if (Features.ONBOARDING_EXPERIENCE.isEnabled(this) && OnboardingUtils.needToShowOnboarding(this)
            && !skipToShowOnboarding && !TvCommonUtils.isRunningInTest()) {
        // TODO: The onboarding is turned off in test, because tests are broken by the
        // onboarding. We need to enable the feature for tests later.
        startActivity(OnboardingActivity.buildIntent(this, getIntent()));
        finish();
        return;
    }

    TvApplication tvApplication = (TvApplication) getApplication();
    tvApplication.getMainActivityWrapper().onMainActivityCreated(this);
    if (BuildConfig.ENG && SystemProperties.ALLOW_STRICT_MODE.getValue()) {
        Toast.makeText(this, "Using Strict Mode for eng builds", Toast.LENGTH_SHORT).show();
    }
    mTracker = tvApplication.getTracker();
    mTvInputManagerHelper = tvApplication.getTvInputManagerHelper();
    mTvInputManagerHelper.addCallback(mTvInputCallback);
    mUsbTunerInputId = UsbTunerTvInputService.getInputId(this);
    mChannelDataManager = tvApplication.getChannelDataManager();
    mProgramDataManager = tvApplication.getProgramDataManager();
    mProgramDataManager.addOnCurrentProgramUpdatedListener(Channel.INVALID_ID,
            mOnCurrentProgramUpdatedListener);
    mProgramDataManager.setPrefetchEnabled(true);
    mChannelTuner = new ChannelTuner(mChannelDataManager, mTvInputManagerHelper);
    mChannelTuner.addListener(mChannelTunerListener);
    mChannelTuner.start();
    mPipInputManager = new PipInputManager(this, mTvInputManagerHelper, mChannelTuner);
    mPipInputManager.start();
    mMemoryManageables.add(mProgramDataManager);
    mMemoryManageables.add(ImageCache.getInstance());
    mMemoryManageables.add(TvContentRatingCache.getInstance());
    if (CommonFeatures.DVR.isEnabled(this) && BuildCompat.isAtLeastN()) {
        mDvrManager = tvApplication.getDvrManager();
        mDvrDataManager = tvApplication.getDvrDataManager();
    }

    DisplayManager displayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
    Display display = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
    Point size = new Point();
    display.getSize(size);
    int screenWidth = size.x;
    int screenHeight = size.y;
    mDefaultRefreshRate = display.getRefreshRate();

    mOverlayRootView = (OverlayRootView) getLayoutInflater().inflate(R.layout.overlay_root_view, null, false);
    setContentView(R.layout.activity_tv);
    mTvView = (TunableTvView) findViewById(R.id.main_tunable_tv_view);
    int shrunkenTvViewHeight = getResources().getDimensionPixelSize(R.dimen.shrunken_tvview_height);
    mTvView.initialize((AppLayerTvView) findViewById(R.id.main_tv_view), false, screenHeight,
            shrunkenTvViewHeight);
    mTvView.setOnUnhandledInputEventListener(new OnUnhandledInputEventListener() {
        @Override
        public boolean onUnhandledInputEvent(InputEvent event) {
            if (isKeyEventBlocked()) {
                return true;
            }
            if (event instanceof KeyEvent) {
                KeyEvent keyEvent = (KeyEvent) event;
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && keyEvent.isLongPress()) {
                    if (onKeyLongPress(keyEvent.getKeyCode(), keyEvent)) {
                        return true;
                    }
                }
                if (keyEvent.getAction() == KeyEvent.ACTION_UP) {
                    return onKeyUp(keyEvent.getKeyCode(), keyEvent);
                } else if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    return onKeyDown(keyEvent.getKeyCode(), keyEvent);
                }
            }
            return false;
        }
    });
    mTimeShiftManager = new TimeShiftManager(this, mTvView, mProgramDataManager, mTracker,
            new OnCurrentProgramUpdatedListener() {
                @Override
                public void onCurrentProgramUpdated(long channelId, Program program) {
                    updateMediaSession();
                    switch (mTimeShiftManager.getLastActionId()) {
                    case TimeShiftManager.TIME_SHIFT_ACTION_ID_REWIND:
                    case TimeShiftManager.TIME_SHIFT_ACTION_ID_FAST_FORWARD:
                    case TimeShiftManager.TIME_SHIFT_ACTION_ID_JUMP_TO_PREVIOUS:
                    case TimeShiftManager.TIME_SHIFT_ACTION_ID_JUMP_TO_NEXT:
                        updateChannelBannerAndShowIfNeeded(UPDATE_CHANNEL_BANNER_REASON_FORCE_SHOW);
                        break;
                    default:
                        updateChannelBannerAndShowIfNeeded(UPDATE_CHANNEL_BANNER_REASON_UPDATE_INFO);
                        break;
                    }
                }
            });

    mPipView = (TunableTvView) findViewById(R.id.pip_tunable_tv_view);
    mPipView.initialize((AppLayerTvView) findViewById(R.id.pip_tv_view), true, screenHeight,
            shrunkenTvViewHeight);

    if (!PermissionUtils.hasAccessWatchedHistory(this)) {
        WatchedHistoryManager watchedHistoryManager = new WatchedHistoryManager(getApplicationContext());
        watchedHistoryManager.start();
        mTvView.setWatchedHistoryManager(watchedHistoryManager);
    }
    mTvViewUiManager = new TvViewUiManager(this, mTvView, mPipView,
            (FrameLayout) findViewById(android.R.id.content), mTvOptionsManager);

    mPipView.setFixedSurfaceSize(screenWidth / 2, screenHeight / 2);
    mPipView.setBlockScreenType(TunableTvView.BLOCK_SCREEN_TYPE_SHRUNKEN_TV_VIEW);

    ViewGroup sceneContainer = (ViewGroup) findViewById(R.id.scene_container);
    mChannelBannerView = (ChannelBannerView) getLayoutInflater().inflate(R.layout.channel_banner,
            sceneContainer, false);
    mKeypadChannelSwitchView = (KeypadChannelSwitchView) getLayoutInflater()
            .inflate(R.layout.keypad_channel_switch, sceneContainer, false);
    InputBannerView inputBannerView = (InputBannerView) getLayoutInflater().inflate(R.layout.input_banner,
            sceneContainer, false);
    SelectInputView selectInputView = (SelectInputView) getLayoutInflater().inflate(R.layout.select_input,
            sceneContainer, false);
    selectInputView.setOnInputSelectedCallback(new OnInputSelectedCallback() {
        @Override
        public void onTunerInputSelected() {
            Channel currentChannel = mChannelTuner.getCurrentChannel();
            if (currentChannel != null && !currentChannel.isPassthrough()) {
                hideOverlays();
            } else {
                tuneToLastWatchedChannelForTunerInput();
            }
        }

        @Override
        public void onPassthroughInputSelected(TvInputInfo input) {
            Channel currentChannel = mChannelTuner.getCurrentChannel();
            String currentInputId = currentChannel == null ? null : currentChannel.getInputId();
            if (TextUtils.equals(input.getId(), currentInputId)) {
                hideOverlays();
            } else {
                tuneToChannel(Channel.createPassthroughChannel(input.getId()));
            }
        }

        private void hideOverlays() {
            getOverlayManager().hideOverlays(TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_DIALOG
                    | TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_SIDE_PANELS
                    | TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_PROGRAM_GUIDE
                    | TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_MENU
                    | TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_FRAGMENT);
        }
    });
    mSearchFragment = new ProgramGuideSearchFragment();
    mOverlayManager = new TvOverlayManager(this, mChannelTuner, mKeypadChannelSwitchView, mChannelBannerView,
            inputBannerView, selectInputView, sceneContainer, mSearchFragment);

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

    mMediaSession = new MediaSession(this, MEDIA_SESSION_TAG);
    mMediaSession.setCallback(new MediaSession.Callback() {
        @Override
        public boolean onMediaButtonEvent(Intent mediaButtonIntent) {
            // Consume the media button event here. Should not send it to other apps.
            return true;
        }
    });
    mMediaSession
            .setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mNowPlayingCardWidth = getResources().getDimensionPixelSize(R.dimen.notif_card_img_max_width);
    mNowPlayingCardHeight = getResources().getDimensionPixelSize(R.dimen.notif_card_img_height);

    mTvViewUiManager.restoreDisplayMode(false);
    if (!handleIntent(getIntent())) {
        finish();
        return;
    }

    mAudioCapabilitiesReceiver = new AudioCapabilitiesReceiver(this,
            new AudioCapabilitiesReceiver.OnAc3PassthroughCapabilityChangeListener() {
                @Override
                public void onAc3PassthroughCapabilityChange(boolean capability) {
                    mAc3PassthroughSupported = capability;
                }
            });
    mAudioCapabilitiesReceiver.register();

    mAccessibilityManager = (AccessibilityManager) getSystemService(Context.ACCESSIBILITY_SERVICE);
    mSendConfigInfoRecurringRunner = new RecurringRunner(this, TimeUnit.DAYS.toMillis(1),
            new SendConfigInfoRunnable(mTracker, mTvInputManagerHelper), null);
    mSendConfigInfoRecurringRunner.start();
    mChannelStatusRecurringRunner = SendChannelStatusRunnable.startChannelStatusRecurringRunner(this, mTracker,
            mChannelDataManager);

    // To avoid not updating Rating systems when changing language.
    mTvInputManagerHelper.getContentRatingsManager().update();

    initForTest();
}

From source file:com.android.tv.MainActivity.java

@Override
protected void onResume() {
    if (DEBUG)/*  ww w  .ja v a2 s. c o m*/
        Log.d(TAG, "onResume()");
    super.onResume();
    if (!PermissionUtils.hasAccessAllEpg(this)
            && checkSelfPermission(PERMISSION_READ_TV_LISTINGS) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[] { PERMISSION_READ_TV_LISTINGS }, PERMISSIONS_REQUEST_READ_TV_LISTINGS);
    }
    mTracker.sendScreenView(SCREEN_NAME);

    SystemProperties.updateSystemProperties();
    mNeedShowBackKeyGuide = true;
    mActivityResumed = true;
    mShowNewSourcesFragment = true;
    mOtherActivityLaunched = false;
    int result = mAudioManager.requestAudioFocus(MainActivity.this, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    mAudioFocusStatus = (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) ? AudioManager.AUDIOFOCUS_GAIN
            : AudioManager.AUDIOFOCUS_LOSS;
    setVolumeByAudioFocusStatus();

    if (mTvView.isPlaying()) {
        // Every time onResume() is called the activity will be assumed to not have requested
        // visible behind.
        requestVisibleBehind(true);
    }
    if (mChannelTuner.areAllChannelsLoaded()) {
        SetupUtils.getInstance(this).markNewChannelsBrowsable();
        resumeTvIfNeeded();
        resumePipIfNeeded();
    }
    mOverlayManager.showMenuWithTimeShiftPauseIfNeeded();

    // Note: The following codes are related to pop up an overlay UI after resume.
    // When the following code is changed, please check the variable
    // willShowOverlayUiAfterResume in updateChannelBannerAndShowIfNeeded.
    if (mInputToSetUp != null) {
        startSetupActivity(mInputToSetUp, false);
        mInputToSetUp = null;
    } else if (mShowProgramGuide) {
        mShowProgramGuide = false;
        mHandler.post(new Runnable() {
            // This will delay the start of the animation until after the Live Channel app is
            // shown. Without this the animation is completed before it is actually visible on
            // the screen.
            @Override
            public void run() {
                mOverlayManager.showProgramGuide();
            }
        });
    } else if (mShowSelectInputView) {
        mShowSelectInputView = false;
        mHandler.post(new Runnable() {
            // mShowSelectInputView is true when the activity is started/resumed because the
            // TV_INPUT button was pressed in a different app.
            // This will delay the start of the animation until after the Live Channel app is
            // shown. Without this the animation is completed before it is actually visible on
            // the screen.
            @Override
            public void run() {
                mOverlayManager.showSelectInputView();
            }
        });
    }
}

From source file:com.android.tv.MainActivity.java

@Override
protected void onPause() {
    if (DEBUG)/*from  ww w . j av a2 s  .c  o  m*/
        Log.d(TAG, "onPause()");
    finishChannelChangeIfNeeded();
    mActivityResumed = false;
    mOverlayManager.hideOverlays(TvOverlayManager.FLAG_HIDE_OVERLAYS_DEFAULT);
    mTvView.setBlockScreenType(TunableTvView.BLOCK_SCREEN_TYPE_NO_UI);
    if (mPipEnabled) {
        mTvViewUiManager.hidePipForPause();
    }
    mBackKeyPressed = false;
    mShowLockedChannelsTemporarily = false;
    mShouldTuneToTunerChannel = false;
    if (!mVisibleBehind) {
        mAudioFocusStatus = AudioManager.AUDIOFOCUS_LOSS;
        mAudioManager.abandonAudioFocus(this);
        if (mMediaSession.isActive()) {
            mMediaSession.setActive(false);
        }
        mTracker.sendScreenView("");
    } else {
        mTracker.sendScreenView(SCREEN_BEHIND_NAME);
    }
    super.onPause();
}

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  ww w . j  av  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);
    }
}

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 ww .  j a  v  a  2s .  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);
    }
}

From source file:com.rks.musicx.services.MusicXService.java

@Override
public void onAudioFocusChange(int focusChange) {
    switch (focusChange) {
    case AudioManager.AUDIOFOCUS_LOSS:
        Log.d(TAG, "AudioFocus Loss");
        if (MediaPlayerSingleton.getInstance().getMediaPlayer().isPlaying()) {
            pause();/*from   w ww. j  av  a2s. co m*/
            //service.stopSelf();
        }
        break;
    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
        if (MediaPlayerSingleton.getInstance().getMediaPlayer().isPlaying()) {
            MediaPlayerSingleton.getInstance().getMediaPlayer().setVolume(0.3f, 0.3f);
            mIsDucked = true;
        }
        Log.d(TAG, "AudioFocus Loss Can Duck Transient");
        break;
    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
        Log.d(TAG, "AudioFocus Loss Transient");
        if (MediaPlayerSingleton.getInstance().getMediaPlayer().isPlaying()) {
            pause();
            mLostAudioFocus = true;
        }
        break;
    case AudioManager.AUDIOFOCUS_GAIN:
        Log.d(TAG, "AudioFocus Gain");
        if (mIsDucked) {
            MediaPlayerSingleton.getInstance().getMediaPlayer().setVolume(1.0f, 1.0f);
            mIsDucked = false;
        } else if (mLostAudioFocus) {
            // If we temporarily lost the audio focus we can resume playback here
            if (MediaPlayerSingleton.getInstance().getMediaPlayer().isPlaying()) {
                play();
            }
            mLostAudioFocus = false;
        }
        break;
    default:
        Log.d(TAG, "Unknown focus");
    }
}