天天看点

用广播监听安卓设备电量状态

用广播监听安卓设备电量状态

这次邮件我们将会讨论怎么获取电量状态在安卓设备上,为了完成这个目标,我们将会使用到广播。

What is BroadcastReceiver?

A broadcast receiver is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android application.

The system itself broadcast event all time, as example when system gets booted or an SMS arrived, etc.

Application description

Application display of battery level and update this value when battery level changed.

用广播监听安卓设备电量状态

在Android Studio 中新建一个工程

用广播监听安卓设备电量状态
用广播监听安卓设备电量状态
用广播监听安卓设备电量状态
用广播监听安卓设备电量状态

在String.xml中添加一个常量

  

更新布局文件,在这里我叫 “activity_main.xml”

创建一个内部类为我们的广播实现

更新Activity的代码如下:

我们必须反注册你的接收者当activity 停止,因为如果不反注册,当你的应用程序关闭时候,进程会一直在后台接受一些信息

 注册广播:

运行程序

We can change battery level of our emulator use console. We must connect to out AVD Emulator use console / terminal. If we run many emulator, each emulator will have unique port. Port number your emulator you can find in title of emulator window. As example port of my emulator is 5554.

Connect to emulator:

telnet localhost <PORT>

Change battery level of emulator:

power capacity <BATTERY_LEVEL_IN_PERCENT>

用广播监听安卓设备电量状态

Next step is change battery level on emulator.

用广播监听安卓设备电量状态

As you can see TextView and ProgressBar were updated.

from:http://alexzh.com/tutorials/android-battery-status-use-broadcastreceiver/?utm_source=Android+Weekly&utm_campaign=bce41f280c-Android_Weekly_149&utm_medium=email&utm_term=0_4eb677ad19-bce41f280c-337902977

继续阅读