我正在尝试监控我的电池状态,但我一直从听众那里获取默认值,这是我的接收器类:
public class BatteryIndicatorListener extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Log.d("battery status", "changed");
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
Log.d("battery status", "chargeplug: "+chargePlug);
Log.d("battery status", "status: "+status);
Log.d("battery status", "is charging: "+isCharging);
Log.d("battery status", "usb charging: "+usbCharge);
Log.d("battery status", "ac charging: "+acCharge);
Log.d("battery status", "level: "+level);
Log.d("battery status", "scale: "+scale);
这是我的logcat输出:
03-18 10:44:50.806: D/battery status(7855): changed
03-18 10:44:50.806: D/battery status(7855): chargeplug: -1
03-18 10:44:50.806: D/battery status(7855): status: -1
03-18 10:44:50.806: D/battery status(7855): is charging: false
03-18 10:44:50.806: D/battery status(7855): usb charging: false
03-18 10:44:50.806: D/battery status(7855): ac charging: false
03-18 10:44:50.806: D/battery status(7855): level: -1
03-18 10:44:50.806: D/battery status(7855): scale: -1
我的清单有这个:
<uses-permission android:name="android.permission.BATTERY_STATS"/>
<uses-permission android:name="android.permission.BROADCAST_STICKY"/>
<receiver android:name="com.zivkesten.find_a_place.control.service.BatteryIndicatorListener" >
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
<action android:name="android.intent.action.BATTERY_CHANGED"/>
<action android:name="android.intent.action.BATTERY_LOW"/>
<action android:name="android.intent.action.BATTERY_OKAY"/>
</intent-filter>
</receiver>
我错过了什么吗?
答案 0 :(得分:3)
试试这个。
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);