Android-obtain battery-related information
1. Define Broadcast Reception and display BatteryInfoBroadcastReceiver
Package org. lxh. demo; import android. app. alertDialog; import android. app. dialog; import android. content. broadcastReceiver; import android. content. context; import android. content. dialogInterface; import android. content. intent; public class BatteryInfoBroadcastReceiver extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) {if (Intent. ACTION_BATTERY_CHANGED.equals (intent. getAction () {int level = intent. getIntExtra (level, 0); int scale = intent. getIntExtra (scale, 0); int voltage = intent. getIntExtra (voltage, 0); int temperature = intent. getIntExtra (temperature, 0); String technology = intent. getStringExtra (technology); Dialog dialog = new AlertDialog. builder (context ). setTitle (battery ). setMessage (battery: + String. valueOf (level * 100/scale) + % + battery voltage: + String. valueOf (float) voltage/1000) + v + Battery Type: + technology ++ battery temperature: + String. valueOf (float) temperature/10) + °C ). setNegativeButton (close, new DialogInterface. onClickListener () {public void onClick (DialogInterface arg0, int arg1 ){}}). create (); dialog. show ();}}}
2. Define the layout manager -- main. xml
3. Define the Activity program:
Package org. lxh. demo; import android. app. activity; import android. app. alertDialog; import android. app. dialog; import android. content. dialogInterface; import android. content. intent; import android. content. intentFilter; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. view. view. onFocusChangeListener; import android. widget. button; import android. widget. editText; import android. widget. textView; public class Hello extends Activity {private Button mybtn = null; public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // life cycle method super. setContentView (R. layout. main); // set the layout manager to use this. mybtn = (Button) super. findViewById (R. id. mybtn); this. mybtn. setOnClickListener (new OnClickListenerImpl ();} private class OnClickListenerImpl implements OnClickListener {public void onClick (View v) {BatteryInfoBroadcastReceiver listener ER = null; receiver ER = new listener (); intentFilter filter = new IntentFilter (Intent. ACTION_BATTERY_CHANGED); Hello. this. registerReceiver (receiver, filter );}}}
The following figure shows the actual running effect on the mobile phone: