我正在开发具有以下所需的应用程序:如果在设备插入耳机和用户删除它,我需要静音所有流。 要做到这一点,我需要听AudioManager.ACTION_AUDIO_BECOMING_NOISY
广播。 还行吧! 没有问题就在这里。
但是,当用户再次插入耳机后 ,我需要取消静音的设备。 但没有一个AudioManager.ACTION_AUDIO_BECOMING_NOISY
相反广播。 当耳机插入再次我不知道。
一个解决办法是定期检查是否AudioManager.isWiredHeadsetOn()
是true
,但是这似乎并没有得到很好的解决了我。
有没有一种方法,当用户插入设备上的耳机来检测?
编辑 :我试图用Intent.ACTION_HEADSET_PLUG
这种方式, 但没有奏效 。
在manifest.xml我把:
<receiver android:name=".MusicIntentReceiver" >
<intent-filter>
<action android:name="android.intent.action.HEADSET_PLUG" />
</intent-filter>
</receiver>
这里是我的代码MusicIntentReceiver.java
:
public class MusicIntentReceiver extends BroadcastReceiver {
public void onReceive(Context ctx, Intent intent) {
AudioManager audioManager = (AudioManager)ctx.getSystemService(Context.AUDIO_SERVICE);
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
Log.d("Let's turn the sound on!");
//other things to un-mute the streams
}
}
}
任何其他解决方案来试试呢?
这样如何调用: http://developer.android.com/reference/android/content/Intent.html#ACTION_HEADSET_PLUG我发现在Droid难以置信耳机检测 ?
更新后的代码,我在你的问题,现在看是不够的。 这广播发生在封堵状态发生变化时,有时当它不,根据Intent.ACTION_HEADSET_PLUG在活动开始时收到的 ,所以我会写:
package com.example.testmbr;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private MusicIntentReceiver myReceiver;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myReceiver = new MusicIntentReceiver();
}
@Override public void onResume() {
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
registerReceiver(myReceiver, filter);
super.onResume();
}
private class MusicIntentReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
Log.d(TAG, "Headset is unplugged");
break;
case 1:
Log.d(TAG, "Headset is plugged");
break;
default:
Log.d(TAG, "I have no idea what the headset state is");
}
}
}
}
@Override public void onPause() {
unregisterReceiver(myReceiver);
super.onPause();
}
}
我前面推荐原来,AudioManager.isWiredHeadsetOn()调用,因为API 14被弃用,因此,我从广播意图提取状态取而代之。 这是可能的,有可能是每个插拔也许是因为在连接器接触反弹,多个广播。
我还没有这个工作,但如果我在看文档吧, ACTION_AUDIO_BECOMING_NOISY
是让一个应用程序知道音频输入可能会开始听到音频输出。 当你拔掉耳机,手机的话筒可能开始拿起电话的扬声器,因此该消息。
在另一方面, ACTION_SCO_AUDIO_STATE_UPDATED
目的是让你知道什么时候有一个蓝牙设备的连接状态的改变。
这第二个可能是你想要听什么。
文章来源: How to detect when a user plugs headset on android device? (Opposite of ACTION_AUDIO_BECOMING_NOISY)