Android receives power from the mobile phone

Source: Internet
Author: User

In android, you can use intent broadcast to monitor the power of your mobile phone.
The following is an example of action_battery_changed:

Java code
Package com. liao;
Import android. app. Activity;
Import android. content. BroadcastReceiver;
Import android. content. Context;
Import android. content. Intent;
Import android. content. IntentFilter;
Import android. OS. Bundle;
Import android. widget. TextView;
 
Public class BatteryLevelActivity extends Activity {
/** Called when the activity is first created .*/
Private TextView batterLevel;
 
@ Override
/**
* Called when the current activity is first created.
*/
Public void onCreate (Bundle icicle ){
Super. onCreate (icicle );
SetContentView (R. layout. main );
BatterLevel = (TextView) this. findViewById (R. id. batteryLevel );
BatteryLevel ();
}
 
Private void batteryLevel (){
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver (){
Public void onReceive (Context context, Intent intent ){
Context. unregisterReceiver (this );
Int rawlevel = intent. getIntExtra ("level",-1); // obtain the current power
Int scale = intent. getIntExtra ("scale",-1 );
// Obtain the total power
Int level =-1;
If (rawlevel> = 0 & scale> 0 ){
Level = (rawlevel * 100)/scale;
}
BatterLevel. setText ("Battery Level Remaining:" + level + "% ");
}
};
IntentFilter batteryLevelFilter = new IntentFilter (Intent. ACTION_BATTERY_CHANGED );
RegisterReceiver (batteryLevelReceiver, batteryLevelFilter );
}

}


If it is 2. The SDK after 0 can also be like this:
Public void onReceive (Context context, Intent intent ){

Context. unregisterReceiver (this );

Int rawlevel = intent. getIntExtra (BatteryManager. EXTRA_LEVEL,-1 );

Int scale = intent. getIntExtra (BatteryManager. EXTRA_SCALE,-1 );

Just modify the class.

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.