查看手机电量

1、创建BroadcastReceiver对象,重写onReceive()方法首先获取Action事件,当判断该事件为Intent.ACTION_BATTERY_CHANGED时,获取手机当前电量和总电量

BroadcastReceiver br=new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String s=intent.getAction();
if(Intent.ACTION_BATTERY_CHANGED.equals(s)){
level=intent.getIntExtra("level", 0);
scale=intent.getIntExtra("scale", 100);
hd.sendEmptyMessage(0);
Toast.makeText(MainActivity.this, "当前电量为:"+level*100/scale+"%", Toast.LENGTH_SHORT).show();
}
}
};

2、创建Handler对象,重写handleMessage()方法,捕捉信息编号为0的消息,更改TextView的内容

Handler hd=new Handler(){
public void handleMessage(Message msg){
switch (msg.what) {
case 0:
TextView tv=(TextView)MainActivity.this.findViewById(R.id.TextView02);
tv.setText(level*100/scale+"%");;
break;

default:
break;
}
}
};

3、在Button的点击事件中注册访问电池剩余量的系统BroadcastReceiver

registerReceiver(br, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

查看手机电量,布布扣,bubuko.com

查看手机电量

上一篇:【转载】如何让Chrome浏览器允许本地环境支持Ajax


下一篇:Java中 “…” 运算符