Get battery charge Instance code _android in Android

Source: Internet
Author: User
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);
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.