Actually I can't see what can be wrong with your code so I have created small test activity.
To test audio focus listener you have to start this activity, minimize it using "Home" button and then start some music player (tested with stock one on emulator) – you should be able to see 'Focus LOST' toast as soon as music starts playing. When you stop the music – you should see 'Focus GAINED' message.
Also, here is a good article about handling audio focus (just leaving it here for future reference)
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private AudioManager mAudioManager;
private AudioFocusChangeListenerImpl mAudioFocusChangeListener;
private boolean mFocusGranted, mFocusChanged;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mAudioFocusChangeListener = new AudioFocusChangeListenerImpl();
int result = mAudioManager.requestAudioFocus(mAudioFocusChangeListener,
AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
switch (result) {
case AudioManager.AUDIOFOCUS_REQUEST_GRANTED:
mFocusGranted = true;
break;
case AudioManager.AUDIOFOCUS_REQUEST_FAILED:
mFocusGranted = false;
break;
}
String message = "Focus request " + (mFocusGranted ? "granted" : "failed");
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
Log.i(TAG, message);
}
@Override
protected void onDestroy() {
super.onDestroy();
mAudioManager.abandonAudioFocus(mAudioFocusChangeListener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class AudioFocusChangeListenerImpl implements AudioManager.OnAudioFocusChangeListener {
@Override
public void onAudioFocusChange(int focusChange) {
mFocusChanged = true;
Log.i(TAG, "Focus changed");
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
Log.i(TAG, "AUDIOFOCUS_GAIN");
Toast.makeText(MainActivity.this, "Focus GAINED", Toast.LENGTH_LONG).show();
break;
case AudioManager.AUDIOFOCUS_LOSS:
Log.i(TAG, "AUDIOFOCUS_LOSS");
Toast.makeText(MainActivity.this, "Focus LOST", Toast.LENGTH_LONG).show();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
Log.i(TAG, "AUDIOFOCUS_LOSS_TRANSIENT");
Toast.makeText(MainActivity.this, "Focus LOST TRANSIENT", Toast.LENGTH_LONG).show();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
Log.i(TAG, "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
Toast.makeText(MainActivity.this, "Focus LOST TRANSIENT CAN DUCK", Toast.LENGTH_LONG).show();
break;
}
}
}
}