问题描述
我正在使用 brad cast reciver 来检测耳机是否连接。这是我的 broadcastReceiver 类。
class HeadsetIntentReceiver: broadcastReceiver() {
override fun onReceive(context: Context?,intent: Intent) {
if (intent.action == Intent.ACTION_HEADSET_PLUG) {
val state = intent.getIntExtra(STATE,NEGATIVE_ONE)
when (state) {
ZERO-> {//Headset not is plugged
}
ONE -> {//Headset is plugged
}
}
}
}
}
registerReceiver(myReceiver,IntentFilter(Intent.ACTION_HEADSET_PLUG))
没关系,但是当设备重新启动时不起作用。我已经检查了一些相关问题,但没有找到解决此问题的任何方法。所以这对我来说是一个全新的问题。
解决方法
您需要在清单中注册广播接收器:
<receiver android:name="yourPath.HeadsetIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_HEADSET_PLUG" />
</intent-filter>
</receiver>
,
像这样注册你的广播接收器
registerReceiver(HeadsetIntentReceiver,IntentFilter(Intent.ACTION_HEADSET_PLUG))