重新启动android后广播接收器不起作用

问题描述

我正在使用 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))

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...