android - context.registerReceiver 在尝试检查电源是否已连接时返回 null Intent

标签 android android-intent android-service battery android-context

我正在尝试检查 Android 设备是否已连接电源。 以下是逻辑(基于 Commonsware 的 stackoverflow 帖子),

Intent intent = context.registerReceiver(null, new IntentFilter(
                    Intent.ACTION_BATTERY_CHANGED));
plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);

它大部分工作正常。然而,根据 Crashlytics 报告,在某些情况下,返回的 Intent 为空,导致应用程序崩溃。我从来没有能够在我的手机上重现它。只是想知道在什么情况下 context.registerReceiver 可能会返回 null?那是因为另一个应用以某种方式持有系统资源,还是我的应用中的另一个线程当时正在访问同一资源?

谢谢 雷

最佳答案

Just wonder under what condition context.registerReceiver might return null?

如果从未有过该Intent 的广播,它将返回null。在这种特殊情况下,它可能表示没有电池的设备(例如 Google TV/Android TV、OUYA)因此会跳过发送广播。或者它可能表示设备上的固件有些损坏(例如,有问题的 ROM 模块、设备制造商的工程错误)。

Is that because somehow another app was holder the system resource, or another thread in my app accessing the same resource at the time?

不,这些应该不是问题。

关于android - context.registerReceiver 在尝试检查电源是否已连接时返回 null Intent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23896936/

相关文章:

android - 具有离线访问和本地安全性和跨平台的类似 Google Drive/Dropbox 的解决方案

android - 抽屉导航自定义适配器不显示图像

android - 将字符串从 edittext 传递到新 Intent 会出现错误

android - 在 fragment 中获取 Intent

Android:使用动画移动位于窗口管理器上的 imageView

android - 使用弹出窗口在 Android 键盘中实现表情符号

android - Phonegap cordova android 'project already exists' 或运行时错误

java - 无法使用 findFragmentById 访问我的 fragment

安卓应用崩溃

android - 为什么在 Android 中调用 stopService 后服务中的线程仍未停止?