3

当我的重复警报广播被调用时,我正在尝试读取 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 页面添加了正确的权限,但这似乎没有帮助。

4

2 回答 2

9

你得到-1levelscale。那是因为您可能正在尝试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;

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

于 2013-02-11T03:22:13.150 回答
2

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

您应该听听以ACTION_BATTERY_CHANGED获取Android 中的电池电量

于 2013-02-11T03:11:27.160 回答