首页 > 系统 > Android > 正文

Android中获取电池电量实例代码

2020-04-11 12:06:35
字体:
来源:转载
供稿:网友
复制代码 代码如下:

/**
*
* @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);
}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表