【问题标题】:Android BatteryManager Returns only 1Android BatteryManager 仅返回 1
【发布时间】:2013-01-26 03:38:50
【问题描述】:

当我的重复警报广播被调用时,我正在尝试读取 Android 电池的状态,我有以下设置:

public class RepeatingAlarm extends BroadcastReceiver {

    @Override       
    public void onReceive(Context context, Intent intent)
    {

            // Acquire the make of the device
            final String PhoneModel = android.os.Build.MODEL;
            final String AndroidVersion = android.os.Build.VERSION.RELEASE;

            // Grab the battery information
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            final float batteryPct = level / (float)scale; 
    }

}

但我不明白为什么它会返回 batteryPct = 1。我在这里缺少什么吗?我根据 android Google 页面添加了正确的权限,但这似乎没有帮助。

【问题讨论】:

    标签: android broadcastreceiver battery repeatingalarm


    【解决方案1】:

    对于levelscale,您将获得-1。 那是因为您可能试图在清单中广播 ACTION_BATTERY_CHANGED

    ACTION_BATTERY_CHANGED 是一个粘性意图,您不能在清单中向它注册接收器。试试下面的

     Intent i = new ContextWrapper(applicationContext).registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
     // now you can get the level and scale from this intent variable
    int level = i.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = i.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    
    float battPct = level/(float)scale;
    

    您不需要为此意图设置接收器,只需使用上述方式,无论您想在哪里使用它。

    【讨论】:

    • 太好了,非常感谢!我不得不对 Intent i 行进行一些小改动,因为它会导致错误(“不允许组件注册以接收意图”)。但现在一切都好。
    • 感谢您提供这段代码。刚刚浪费了 2-3 个小时才找到,为什么我没有在清单上声明的广播接收器上获得有关电池的信息。
    【解决方案2】:

    levelscale 变量(您指定的默认值)可能都为 -1,因此请尝试打印它们的值以确保 intent 正确设置了这些值。

    你应该听ACTION_BATTERY_CHANGEDget battery level in Android

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      • 2017-07-15
      • 2011-12-27
      • 1970-01-01
      • 1970-01-01
      • 2018-10-15
      相关资源
      最近更新 更多