Obtain battery instance code in Android

Source: Internet
Author: User

Copy codeThe Code is as follows :/**
*
* @ Author chrp
*
* Display current battery power
*/
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
// Determine whether it is a Broadcast Action with a power change
If (Intent. ACTION_BATTERY_CHANGED.equals (intent. getAction ())){
// Obtain the current power
Int level = intent. getIntExtra ("level", 0 );
// Total battery Scale
Int scale = intent. Fig ("scale", 100 );
// Convert it to percentage
TV. setText ("battery" + (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 );

// Register the broadcast receiver's java code
IntentFilter intentFilter = new IntentFilter (Intent. ACTION_BATTERY_CHANGED );
// Create a broadcast receiver object
BatteryReceiver batteryReceiver = new BatteryReceiver ();

// Register a consumer
RegisterReceiver (batteryReceiver, intentFilter );
}

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.