如何确定耳机是否已插入 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/