Android设备电量监控

来源:互联网 发布:淘宝图片切片工具 编辑:程序博客网 时间:2024/05/08 23:04

这章介绍的是如何通过广播监听设备

这个很简单不用太多介绍,直接看代码


/** * 电量监控 *  * @author user *  */public class BatteryActivity extends Activity implements OnClickListener {private Button startBtn, stopBtn;private TextView batteryValue;private BroadcastReceiver mReceiver;private IntentFilter mFilter;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.battery_layout);startBtn = (Button) findViewById(R.id.start_btn);stopBtn = (Button) findViewById(R.id.stop_btn);batteryValue = (TextView) findViewById(R.id.battery_vaule);batteryValue.setTextColor(Color.RED);startBtn.setOnClickListener(this);stopBtn.setOnClickListener(this);mFilter = new IntentFilter();// 监听电量变化,只能采用动态注册方式,不能在AndroidManifest.xml中用静态注册广播接受者mFilter.addAction(Intent.ACTION_BATTERY_CHANGED);mReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stub// BatteryManager 包含了Intent.ACTION_BATTERY_CHANGED所需的String和常量值// 当前电量int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);// 最大电量int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);batteryValue.setText("当前电量为:" + (level * 100) / scale + "%");}};}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubint id = v.getId();switch (id) {case R.id.start_btn:registerReceiver(mReceiver, mFilter);break;case R.id.stop_btn:unregisterReceiver(mReceiver);break;default:break;}}@Overrideprotected void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();unregisterReceiver(mReceiver);}}

布局文件

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <Button        android:id="@+id/start_btn"        android:layout_width="100dp"        android:layout_height="50dp"        android:text="start" />    <Button        android:id="@+id/stop_btn"        android:layout_width="100dp"        android:layout_height="50dp"        android:text="stop" />    <TextView        android:id="@+id/battery_vaule"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textSize="20sp" /></LinearLayout>

这样就能时时的获取电量的变化信息,当然也可以通过BatteryManager对象里面的其他String 来获取其他信息,比如EXTRA_PLUGGED,这个是返回当前是用usb,交流电,无线电的方式等

原创粉丝点击