/*** Detect phone charge change * Use Registerreceiver (receiver, Intentfilter) to register the broadcast instead of registering in the manifest file <receiver><receiver> * required Add Permission: * <uses-permission android:name= "Android.permission.BATTERY_STATS"/> * Register the broadcast in Onresume () * Registerreceiver (receiver, intentfilter); * Cancel the broadcast * UNREGISTERRECEIVER (receiver) in OnPause (); * Detection of processing power changes in the broadcast receiver * Detection intent charge change: intent.action_battery_changed * * get current charge * int level = Intent.getintextra ("level", 0 ); * Get total charge * int scale = Intent.getintextra (' scale ', 100); * * */ Public classMainactivityextendsActivity {TextView TV; Privatebroadcastreceiver Receiver; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); TV=(TextView) Findviewbyid (r.id.tv); } @Overrideprotected voidOnresume () {Super. Onresume (); Receiver=NewMyreceiver (); //Intent Filter, filter charge changeIntentfilter Intentfilter =NewIntentfilter (intent.action_battery_changed); //register a broadcast recipientRegisterreceiver (receiver, intentfilter); } @Overrideprotected voidOnPause () {Super. OnPause (); //unregister a broadcast recipientUnregisterreceiver (receiver); } /*** Broadcast Recipient*/ Private classMyreceiverextendsBroadcastreceiver {@Override Public voidOnReceive (Context context, Intent Intent) {if(Intent.getaction (). Equals (intent.action_battery_changed)) {//System's Power change ACTION//current charge "level" intLevel = Intent.getintextra ("level", 0); //Total Power intScale = Intent.getintextra ("scale", 100); //ShowTv.settext ("Current Charge" + (level *)/scale + "%"); } } }}
Broadcat Monitor Power changes