[Java]
/*
* Obtain the remaining batteries of the mobile phone.
* BroadcastReceiver (Android. content. BroadcastReceiver) in the Android API)
* The class is a bit like the Listener in the Button. When the Receiver is registered, it will wait for other programs in the background.
* The program will capture the system by registering the IntentFilter set during BroadcastReceiver.
* The Intent. ACTION_BATTERY_CHANGED action is sent, and the remaining cell phone battery is obtained.
* Margin.
*/
Import omitted;
[Java]
Public class Ex06_02Activity extends Activity {
Private int intLevel;
Private int intScale;
Private Button mButton01;
Private AlertDialog d;
// Create a BroadcastReceiver
Private BroadcastReceiver mBatInfoReveiver = new BroadcastReceiver (){
@ Override
Public void onReceive (Context context, Intent intent ){
// TODO Auto-generated method stub
String action = intent. getAction ();
// If the captured action is ACRION_BATTERY_CHANGED
// Run onBatteryInfoReveiver ()
If (intent. ACTION_BATTERY_CHANGED.equals (action )){
IntLevel = intent. getIntExtra ("level", 0 );
IntScale = intent. getIntExtra ("scale", 100 );
OnBatteryInfoReceiver (intLevel, intScale );
}
}
};
/** Called when the activity is first created .*/
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
MButton01 = (Button) findViewById (R. id. myButton1 );
MButton01.setOnClickListener (new OnClickListener (){
@ Override
Public void onClick (View v ){
// TODO Auto-generated method stub
// Register a BroadcastReceiver for battery measurement.
RegisterReceiver (mBatInfoReveiver, new IntentFilter (
Intent. ACTION_BATTERY_CHANGED ));
}
});
}
// The Action to be executed after ACTION_BATTRY_CHANGED is intercepted
Private void onBatteryInfoReceiver (int intLevel, int intScale ){
// TODO Auto-generated method stub
D = new AlertDialog. Builder (Ex06_02Activity.this). create ();
D. setTitle (R. string. str_dialog_title );
D. setMessage (getResources (). getString (R. string. str_dialog_body)
+ String. valueOf (intLevel * 100/intScale) + "% ");
D. setButton (getResources (). getString (R. string. str_button2 ),
New DialogInterface. OnClickListener (){
@ Override
Public void onClick (DialogInterface dialog, int which ){
// TODO Auto-generated method stub
// Cancel registration and close the dialog box
UnregisterReceiver (mBatInfoReveiver );
D. dismiss ();
}
});
D. show ();
};
}
Next let's take a look at the results after the program runs: www.2cto.com
As mentioned in the Android API, the handler to register Intent. ACTION_BATTERY_CHANGED can only use
The Context. register aggreger () method is used for registration, but cannot be directly registered in AndroidManifest. xml.
Author: Jasonzhou613