如何检测用户何时在安卓设备上插入耳机?(与ACTION_AUDIO_BECOMING_NOISY相反)



我正在开发一个具有以下条件的应用程序:如果设备中插入了耳机并且用户将其移除,则需要将所有流静音。为此,我需要收听AudioManager.ACTION_AUDIO_BECOMING_NOISY广播。这没关系!这里没有问题。

但是当用户再次插入耳机时,我需要取消设备静音。但是没有AudioManager.ACTION_AUDIO_BECOMING_NOISY相反的广播。我不知道耳机何时再次插入。

一种解决方案是定期查看AudioManager.isWiredHeadsetOn()是否true但这对我来说似乎不是一个好的解决方案。

有没有办法检测用户何时在设备上插入耳机?

编辑:我试图以这种方式使用Intent.ACTION_HEADSET_PLUG但它不起作用

在清单中.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我在机器人令人难以置信的耳机检测?

我现在在您的问题中看到的更新代码还不够。该广播发生在插入状态更改时,有时当它没有更改时,根据活动开始时收到的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旨在让您知道蓝牙设备的连接状态何时发生变化。

第二个可能是你想听的。

最新更新