Android Developers can use the broadcastreceiver mechanism to obtain the action_battery_changed intent of the battery change, and then obtain the battery status of the current Android device.
Procedure:
1. Create an intentfilter that listens to the action_battery_changed event.
2. Create a broadcastreceiver object that can receive broadcast intent.
3. register the broadcastreceiver object to listen to the action_battery_changed event.
4. In the broadcastreceiver object, override the onreceive method and obtain the required Battery status information from the input parameter intent of the onreceive method.
5. When the lifecycle ends, cancel the registration in step 4.
Package COM. chen. battery; import android. OS. batterymanager; import android. OS. bundle; import android. app. activity; import android. content. broadcastreceiver; import android. content. context; import android. content. intent; import android. content. intentfilter; import android. view. menu; import android. view. textureview; import android. widget. textview; public class mainactivity extends activity {@ overrideprotected void ondestroy () {// todo auto-generated method stubsuper. ondestroy ();} private textview batterlevel; private broadcastreceiver batterylevelrcvr; private intentfilter batterylevelfilter; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); batterlevel = (textview) findviewbyid (R. id. batterylevel); monitorbatterystate ();} private void monitorbatterystate () {batterylevelrcvr = new broadcastreceiver () {@ overridepublic void onreceive (context, intent) {// todo auto-generated method stubstringbuilder sb = new stringbuilder (); int rawlevel = intent. getintextra ("level",-1); int scale = intent. getintextra ("scale",-1); int status = intent. getintextra ("status",-1); int health = intent. getintextra ("health",-1); int level =-1; if (rawlevel> = 0 & scale> 0) {level = (rawlevel * 100)/scale ;} SB. append ("Battery status:"); sb. append (LEVEL + "%"); Switch (Status) {Case batterymanager. battery_status_unknown: Sb. append ("[No battery installed]"); break; Case batterymanager. battery_status_charging: Sb. append ("[charging]"); break; default: If (level <= 10) Sb. append ("[low power, please charge]"); else if (level <= 100) {sb. append ("[charger not connected]");} break;} sb. append (''); batterlevel. settext (sb. tostring () ;}}; batterylevelfilter = new intentfilter (intent. action_battery_changed); registerreceiver (batterylevelrcvr, batterylevelfilter );}}