Here is a code sample that explains how to get battery information.
To sum it up, a broadcast receiver for the ACTION_BATTERY_CHANGED
intent is set up dynamically, because it can not be received through components declared in manifests, only by explicitly registering for it with Context.registerReceiver()
.
public class Main extends Activity {
private TextView batteryTxt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context ctxt, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level * 100 / (float)scale;
batteryTxt.setText(String.valueOf(batteryPct) + "%");
}
};
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.main);
batteryTxt = (TextView) this.findViewById(R.id.batteryTxt);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…