android - 检测耳机是否插入 Android 设备。

标签 android audio android-intent

如何确定耳机是否已插入 Android 设备?

最佳答案

您可以使用广播接收器。

因此,您可以在“AndroidManifest.xml”中编写此代码

<receiver android:name="com.juno.brheadset.HeadsetStateReceiver">
    <intent-filter>
        <action android:name="android.intent.action.HEADSET_PLUG"/>
    </intent-filter>
</receiver>-->

但是,这不起作用。当操作系统发送此“HEADSET_PLUG” Intent 时,操作系统设置标志“Intent.FLAG_RECEIVER_REGISTERED_ONLY”因此,您应该在 Activity 或 Service 类中编写如下代码,而不是“AndroidManifest”。

public class BRHeadsetActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    HeadsetStateReceiver receiver = new HeadsetStateReceiver();
    registerReceiver( receiver, receiverFilter );


}

希望这篇文章对你有所帮助。再见!

这是“HeadsetObserver.java”的一部分,Android SDK Source。

private final void sendIntent(int headset, int headsetState, int prevHeadsetState, String headsetName) {
    if ((headsetState & headset) != (prevHeadsetState & headset)) {
        //  Pack up the values and broadcast them to everyone
        Intent intent = new Intent(Intent.ACTION_HEADSET_PLUG);

        **intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);**

        int state = 0;
        int microphone = 0;

        if ((headset & HEADSETS_WITH_MIC) != 0) {
            microphone = 1;
        }
        if ((headsetState & headset) != 0) {
            state = 1;
        }
        intent.putExtra("state", state);
        intent.putExtra("name", headsetName);
        intent.putExtra("microphone", microphone);

        if (LOG) Slog.v(TAG, "Intent.ACTION_HEADSET_PLUG: state: "+state+" name: "+headsetName+" mic: "+microphone);
        // TODO: Should we require a permission?
        ActivityManagerNative.broadcastStickyIntent(intent, null);
    }
}

关于android - 检测耳机是否插入 Android 设备。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6249023/

相关文章:

java - 如何使用 volley 库访问 restful web 服务方法

android - keystore 文件错误 :Execution failed for task ':app:validateSigningRelease'

audio - 在哪里可以找到 nw.js 0.12.0 的 ffmpegsumo 库? (在Nodewebkit中播放音频文件)

javascript - HTML 音频录制到静音?

java - 单击菜单项按钮时打开新 Activity 不起作用

android - Paint.breakText() 计算字形,而不是字符

android - 在 imageview 上设置 onclicklistener

audio - 如何对重新采样的音频数据进行双三次(或其他非线性)插值?

android - 如果从菜单调用 Activity ,如何使用 onActivityResult(..)

java - 应用程序在按下按钮时崩溃,并显示 "Attempt to invoke virtual method"