Android设备电量监控
16lz
2021-01-23
这章介绍的是如何通过广播监听设备
这个很简单不用太多介绍,直接看代码
/** * 电量监控 * * @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,交流电,无线电的方式等
更多相关文章
- android获取CPU参数(命令行方式)
- Android使用okHttp(get方式)登录
- Android分享到腾讯微博,信息,新浪微博等等,的实现方式
- 实时获取Android 各版本电量的统一方法
- 第四例:Intent启动Activity的几种方式(一)
- Android Studio 中module需要单独引用jdk的方式
- android 栈方式退出
- 绑定方式开始服务&调用服务的方法
- android加载文件的方式,路径的写法