我正在开发一个具有以下必要条件的应用程序:如果设备中插入了耳机并且用户将其删除,我需要将所有流静音。要做到这一点,我需要听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
}
}
}
还有其他尝试吗?
答案 0 :(得分:81)
这个电话怎么样: http://developer.android.com/reference/android/content/Intent.html#ACTION_HEADSET_PLUG 我找到了 Droid Incredible Headphones Detection ?
我现在在你的问题中看到的更新代码是不够的。根据{{3}},当插入状态发生变化时,有时会发生这种广播,所以我会写:
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以来已被弃用,因此我将其替换为从广播意图中提取状态。每次插拔或拔出可能会有多个广播,可能是因为连接器中的触点反弹。
答案 1 :(得分:2)
我没有使用过这个,但是如果我正确阅读文档,ACTION_AUDIO_BECOMING_NOISY
就是让应用知道音频输入可能会开始听到音频输出。当您拔下耳机时,手机的麦克风可能会开始拿起手机的扬声器,因此会收到消息。
另一方面,ACTION_SCO_AUDIO_STATE_UPDATED
旨在让您知道蓝牙设备的连接状态何时发生变化。
第二个可能是你想听的。