Reputation: 8985
I want my music player to pause music when the ear-phones are disconnected, and to resume music when the ear phones are re-connected. I got this set up to work with a broad cast receiver, but the problem is I can hear music playing from the speakers a split second after I disconnect the ear phones. It's like my receiver is not receiving the broad cast quickly enough? What's going on?
Here I register my receiver in my onCreate
method in my main activity class
MusicIntentReceiver receiver = new MusicIntentReceiver();
registerReceiver(receiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
Here is my intent receiver class
public class MusicIntentReceiver extends android.content.BroadcastReceiver {
@Override
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().equals(android.media.AudioManager.ACTION_HEADSET_PLUG)) {
if(intent.getIntExtra("state",0)==0){ // 0 for unplugged (if it becomes unplugged)
//Pause music
}
if(intent.getIntExtra("state",0)==1){ // 1 for plugged (if it becomes plugged)
//Resume music
}
}
}
}
Upvotes: 2
Views: 579
Reputation: 13343
Try to Pause music on AudioManager.ACTION_AUDIO_BECOMING_NOISY
- it it comes before AudioManager.ACTION_HEADSET_PLUG
(approx. about 1 sec). Something like:
IntentFilter filter = new IntentFilter();
filter.addAction(AudioManager.ACTION_HEADSET_PLUG);
filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
registerReceiver(receiverHeadset, filter);
...
public class MusicIntentReceiver extends android.content.BroadcastReceiver {
@Override
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
// Pause music
} else if (intent.getAction().equals(android.media.AudioManager.ACTION_HEADSET_PLUG)) {
if(intent.getIntExtra("state",0)==1){ // 1 for plugged (if it becomes plugged)
//Resume music
}
}
}
}
Upvotes: 2