Real-time monitoring of the phone's battery power and boot-up capability in the Android system is achieved through the Broadcastreceiver component. We can dynamically register an instance of this class through the Context.registerreceiver () method or statically register through <Receiver> tag in androidmanifest. Xml. Note: If we register a receiver in the activity.onresume () implementation, we should unregister the activity in the activity life cycle of the OnPause method. (This will reduce unnecessary system overhead). Remember that you cannot unregister the activity at Onsaveinstancestate () because this method will not be started until the user returns to the history stack. Below we use the dynamic registration Broadcastreceiver to realize the power monitoring.
(1) Adding permissions in the manifest file
<uses-permission android:name="android.permission.BATTERY_STATS"/>
(2) Register to cancel receiver during activity life cycle
@Overrideprotected voidOnresume () {//TODO auto-generated Method StubSuper.onresume (); Reciver=NewBatterybroadcastreciver (); //Create a filterIntentfilter intentfilter=NewIntentfilter (intent.action_battery_changed); Registerreceiver (Reciver, Intentfilter); } @Overrideprotected voidOnPause () {//TODO auto-generated Method StubSuper.onpause (); Unregisterreceiver (reciver); }
(3) Inherit Broadcastreceiver interface
@Override Public voidOnReceive (Context context, Intent Intent) {//TODO auto-generated Method Stub if(Intent.getaction (). Equals (intent.action_battery_changed)) {//get the current power of the system intLevel=intent.getintextra (" Level",0); //Get total system power intTotal=intent.getintextra (" Scale", -); Textview.settext ("Current charge:"+ (level* -)/total+"%"); //triggered when the charge is less than 15% if(level< the) {Toast.maketext (mainactivity. This,"current charge is less than 15%", Toast.length_long). Show (); } } } }
Android broadcastreceiver Monitor power in real time