英文:
How to detect if headphones was disconnected while media is playing
问题
Sure, here's the translation:
如何在媒体正在播放时检测耳机是否已断开连接...是否有用于此的状态监听器?
以及如何检测耳机何时连接?
英文:
How do I detect if the headphone was disconnected while the media is currently playing....Is there a state listener for that?
And how do I detect when the headphone is connected?
答案1
得分: 2
根据这个链接,您可以创建一个BroadcastReceiver
,用于检测当耳机插入或拔出时发送的意图。
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (Intent.ACTION_HEADSET_PLUG.equals(action)) {
pluggedState = intent.getIntExtra("state", -1);
if (pluggedState == 0) {
// 未插入耳机
}
if (pluggedState == 1) {
// 已插入耳机
}
}
}
};
请注意,Intent.ACTION_HEADSET_PLUG
是通过粘性广播发送的,这意味着一旦注册广播接收器(通常在启动活动时),您将会收到来自上次意图更新的值。有关更多详细信息,请参见这个问题。
英文:
According to this link, you can create a BroadcastReceiver
that checks for an intent sent when headphones are plugged or unplugged.
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (Intent.ACTION_HEADSET_PLUG.equals(action)) {
pluggedState = intent.getIntExtra("state", -1);
if (pluggedState == 0) {
// headset not plugged in
}
if (pluggedState == 1) {
// headset plugged in
}
}
}
};
Note that Intent.ACTION_HEADSET_PLUG
is sent by a sticky broadcast, meaning that as soon as the broadcast receiver is registered (likely when the activity is started), you will receive a value from the last time the intent was updated. See this question for more details.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论