我正在嘗試開發一款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);
}
}
https://stackoverflow.com/a/3586233/3364266此鏈接可以幫助你 –
@SamirBhatt感謝您的鏈接,但這個問題的答案建議使用AudioManager .OnAudioFocusChangeListener這是我上面嘗試過的。也許我使用的服務是錯誤的。 –