获得电池电量

时间:2014-07-16 22:50:25

标签: android broadcast batterylevel

我试图获得电池状态。我使用这段代码:

public class BatteryLevelReceiver extends BroadcastReceiver {
SharedPreferences prefs;
int scale = -1;
int level = -1;

@Override
public void onReceive(Context context, Intent intent) {
    prefs = PreferenceManager.getDefaultSharedPreferences(context);
    level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    // temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
    // voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
    float nivel = level / (float) scale;
    Log.e("level",level+"");
    Log.e("scale",scale+"");
    Log.e("batteryLevel",nivel+"");
}
AndroidManifest.xml中的

    <uses-permission android:name="android.permission.BATTERY_STATS" />

<receiver android:name="com.spg.receiver.BatteryLevelReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.BATTERY_LOW" />
            <action android:name="android.intent.action.BATTERY_OKAY" />
        </intent-filter>
    </receiver>

使用该代码,我得到了这些线程:

Get battery level and state in Android

BatteryManager stats not working on Android

但每次,等级和等级的值都为-1。

我不知道自己错过了什么......

1 个答案:

答案 0 :(得分:2)

BatteryManagerACTION_BATTERY_CHANGED Intent而非BATTERY_LOWBATTERY_OKAY提供常量。此外,ACTION_BATTERY_CHANGED必须以编程方式注册,您可以在onCreate中执行此操作。由于BroadcastReceiver无法接收,因此请确保您不需要使用Service,例如您需要在启动时接收电池事件。