我正在尝试开发一个Android应用程序,即使应用程序最小化,也会在任何应用程序开始播放音频时显示弹出窗口。
到目前为止,我尝试使用带有onAudioFocusChange侦听器的服务,但从不调用侦听器。以下是我到目前为止的情况:
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("AUDIO", "SERVICE STARTED"); //CALLED
AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
AudioManager.OnAudioFocusChangeListener listener = new AudioManager.OnAudioFocusChangeListener(){
@Override
public void onAudioFocusChange(int i) {
Log.i("AUDIO", "FOCUS CHANGED"); //NOT CALLED
}
};
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
我是在正确的轨道上吗?
编辑: 尝试按照建议注册听众,但仍然无法正常工作。即使是在主要活动中。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.test);
Button btnPlay1 = (Button) findViewById(R.id.btn_play_1);
btnPlay1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mediaPlayer.start();
}
});
AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
AudioManager.OnAudioFocusChangeListener listener = new AudioManager.OnAudioFocusChangeListener(){
@Override
public void onAudioFocusChange(int i) {
Log.i("AUDIO", "FOCUS CHANGED"); //NOT CALLED
}
};
am.requestAudioFocus(listener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN );
}
}
答案 0 :(得分:2)
您刚刚在代码中声明了侦听器,但未注册它。 你需要注册
am.requestAudioFocus(listener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN );
检查this