Android中获取电池电量实例代码
程序员文章站
2023-08-12 19:50:40
复制代码 代码如下: /** * * @author chrp * *显示当前电池电量 */ public class mainactivity extends activ...
复制代码 代码如下:
/**
*
* @author chrp
*
*显示当前电池电量
*/
public class mainactivity extends activity {
private textview tv;
/**
* 广播接受者
*/
class batteryreceiver extends broadcastreceiver{
@override
public void onreceive(context context, intent intent) {
// todo auto-generated method stub
//判断它是否是为电量变化的broadcast action
if(intent.action_battery_changed.equals(intent.getaction())){
//获取当前电量
int level = intent.getintextra("level", 0);
//电量的总刻度
int scale = intent.getintextra("scale", 100);
//把它转成百分比
tv.settext("电池电量为"+((level*100)/scale)+"%");
}
}
}
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
//setcontentview(r.layout.activity_main);
tv = new textview(this);
tv.settext("chrp");
this.setcontentview(tv);
//注册广播接受者java代码
intentfilter intentfilter = new intentfilter(intent.action_battery_changed);
//创建广播接受者对象
batteryreceiver batteryreceiver = new batteryreceiver();
//注册receiver
registerreceiver(batteryreceiver, intentfilter);
}
上一篇: 香椿怎么淹好吃家常做法一学就会