我试图获得电池状态。我使用这段代码:
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。
我不知道自己错过了什么......
答案 0 :(得分:2)
BatteryManager为ACTION_BATTERY_CHANGED Intent
而非BATTERY_LOW
或BATTERY_OKAY
提供常量。此外,ACTION_BATTERY_CHANGED
必须以编程方式注册,您可以在onCreate
中执行此操作。由于BroadcastReceiver
无法接收,因此请确保您不需要使用Service
,例如您需要在启动时接收电池事件。