activity_main.xml中
<?xml version="1.0" encoding="utf-8"?> < LinearLayout xmlns: android= " http://schemas.android.com/apk/res/android" android: layout_width= " match_parent" android: layout_height= " match_parent" android: orientation= " vertical" > < Buttonandroid: id= " @+id/register_btn" android: layout_width= " match_parent" android: layout_height= " wrap_content" android: text= " StartListenerBattery" /> < TextViewandroid: id= " @+id/battery_value" android: layout_width= " match_parent" android: layout_height= " wrap_content" android: textSize= " 20sp" android: textColor= " #FF0000" android: gravity= " center" />
</ LinearLayout>
MainActivity中
public class MainActivity extends Activity { private BatteryChangedReceiver batteryChangedReceiver; private IntentFilter intentFilter1; private Button registerBtn; private TextView batteryValue; @Override protected void onCreate ( Bundle savedInstanceState) { super . onCreate ( savedInstanceState) ; setContentView ( R . layout. activity_main) ; batteryValue = ( TextView ) findViewById ( R . id. battery_value) ; registerBtn = ( Button ) findViewById ( R . id. register_btn) ; batteryChangedReceiver = new BatteryChangedReceiver ( ) ; intentFilter1 = new IntentFilter ( ) ; intentFilter1. addAction ( Intent . ACTION_BATTERY_CHANGED ) ; registerBtn. setOnClickListener ( new View. OnClickListener ( ) { @Override public void onClick ( View view) { registerReceiver ( batteryChangedReceiver, intentFilter1) ; } } ) ; } class BatteryChangedReceiver extends BroadcastReceiver { @Override public void onReceive ( Context context, Intent intent) { int level = intent. getIntExtra ( BatteryManager . EXTRA_LEVEL , 0 ) ; int scale = intent. getIntExtra ( BatteryManager . EXTRA_SCALE , 0 ) ; batteryValue. setText ( "当前电量:" + level* 100 / scale+ "%" ) ; } } @Override protected void onDestroy ( ) { super . onDestroy ( ) ; unregisterReceiver ( batteryChangedReceiver) ; }
}
结果(debug里)