這次郵件我們将會讨論怎麼擷取電量狀态在安卓裝置上,為了完成這個目标,我們将會使用到廣播。
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