【问题标题】:Broadcast Receiver not working after reboot android重启android后广播接收器不工作
【发布时间】:2021-06-30 07:36:19
【问题描述】:

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

没关系,但是当设备重新启动时不起作用。我已经检查了一些相关问题,但没有找到任何解决此问题的方法。所以这对我来说是一个全新的问题。

【问题讨论】:

  • 好吧,考虑到重启后你的应用程序还没有运行,你还没有注册你的接收器。您需要至少运行一次您的应用程序,或者收听系统启动广播并注册您的接收器

标签: java android kotlin broadcastreceiver reboot


【解决方案1】:

您需要在清单中注册广播接收器:

 <receiver android:name="yourPath.HeadsetIntentReceiver">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_HEADSET_PLUG" />
            </intent-filter>
 </receiver>

【讨论】:

    【解决方案2】:

    像这样注册你的广播接收器

    registerReceiver(HeadsetIntentReceiver, IntentFilter(Intent.ACTION_HEADSET_PLUG))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      相关资源
      最近更新 更多