如何在播放媒体时检测耳机是否已断开连接

huangapple go评论130阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年9月2日 23:29:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63708751.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定