• Android学习手记(4) BroadcastReceiver监听电池信息


    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 }

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    ubuntu的apt
    sudo命令
    MySQL导出数据到csv文件
    MySQL导出数据到文件报错
    git_backup.py gitlab项目备份
    java中图像与数组转换
    mongodb转elasticsearch
    impyla-0.14.2.2安装注意事项
    python3.7.3升级 with-openssl openssl-1.0.2a
    hadoop自带性能测试
  • 原文地址:https://www.cnblogs.com/doodle777/p/Android_BroadcastReceiver.html
Copyright © 2020-2023  润新知