我想在我的应用中显示电池电量统计信息。我们怎样才能获得电池电量,电池电压等信息?
答案 0 :(得分:3)
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
int rawlevel = intent.getIntExtra("level", -1);
int scale = intent.getIntExtra("scale", -1);
int level = -1;
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale; /* This is your battery level */
}
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}
或查看这个人(谁写了我发布的代码):http://mihaifonoage.blogspot.com/2010/02/getting-battery-level-in-android-using.html
答案 1 :(得分:3)
this有任何帮助吗?
public class Main extends Activity {
private TextView contentTxt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
int level = intent.getIntExtra("level", 0);
contentTxt.setText(String.valueOf(level) + "%");
}
};
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
contentTxt = (TextView) this.findViewById(R.id.monospaceTxt);
this.registerReceiver(this.mBatInfoReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
}
另请参阅this。