Copy Code code as follows:
/**
*
* @author CHRP
*
* Display current battery charge
*/
public class Mainactivity extends activity {
Private TextView TV;
/**
* Broadcast Recipient
*/
Class Batteryreceiver extends broadcastreceiver{
@Override
public void OnReceive (context context, Intent Intent) {
TODO auto-generated Method Stub
To determine if it's a broadcast Action for a change in electricity
if (Intent.ACTION_BATTERY_CHANGED.equals (Intent.getaction ())) {
Get current charge
int level = Intent.getintextra ("level", 0);
The total scale of the charge
int scale = Intent.getintextra ("scale", 100);
Turn it into a percentage
Tv.settext ("Battery charge is" + ((level*100)/scale) + "%");
}
}
}
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
TV = new TextView (this);
Tv.settext ("CHRP");
This.setcontentview (TV);
Registering broadcast recipient Java code
Intentfilter intentfilter = new Intentfilter (intent.action_battery_changed);
Create a broadcast recipient object
Batteryreceiver batteryreceiver = new Batteryreceiver ();
Register receiver
Registerreceiver (Batteryreceiver, Intentfilter);
}