Android 中,Broadcast是一种在应用程序之间进行传输信息的机制。BroadcastReceiver对发送过来的Broadcast进行过滤和响应。根据这种机制,我们可以获取电池现有电量等信息。
1、实例化BroadcastReceiver
在接受信息的时候,可以通过intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)来判断接收的信息是否为电池电量变化信息。如果是,就获取此信息的详细情况。
1 private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() { 2 @Override 3 public void onReceive(Context context, Intent intent) { 4 if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){ 5 int level = intent.getIntExtra("level", 0); 6 int scale = intent.getIntExtra("scale", 100); 7 batteryView.setText("BatteryLevel " + String.valueOf(level*100/scale)+"%"); 8 } 9 } 10 };
2、注册消息接收器
在onResume方法内注册消息接收器用来接收消息
registerReceiver(batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
3、注销消息接收器
在onPause方法内注销消息接收器
unregisterReceiver(batteryInfoReceiver);
4、完整代码
1 public class MainActivity extends AppCompatActivity { 2 3 private TextView batteryView; 4 private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() { 5 @Override 6 public void onReceive(Context context, Intent intent) { 7 if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){ 8 int level = intent.getIntExtra("level", 0); 9 int scale = intent.getIntExtra("scale", 100); 10 batteryView.setText("BatteryLevel " + String.valueOf(level*100/scale)+"%"); 11 } 12 } 13 }; 14 15 @Override 16 protected void onCreate(Bundle savedInstanceState) { 17 super.onCreate(savedInstanceState); 18 setContentView(R.layout.activity_main); 19 20 batteryView = (TextView) this.findViewById(R.id.batteryView); 21 } 22 23 @Override 24 protected void onResume(){ 25 super.onResume(); 26 registerReceiver(batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); 27 } 28 29 @Override 30 protected void onPause(){ 31 super.onPause(); 32 unregisterReceiver(batteryInfoReceiver); 33 } 34 }
版权声明:本文为博主原创文章,未经博主允许不得转载。