Broadcast receiver - monitoring the Battery Level and Charging State

前端 未结 7 2085
逝去的感伤
逝去的感伤 2020-12-31 23:40

I am trying to make two toasts: one when the device is charging, and one when it`s not. But the receiver acting crazy, sending many toasts, and crashing the app. I can not f

相关标签:
7条回答
  • 2020-12-31 23:49

    you can use this code

      IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = this.registerReceiver(null, ifilter);
    
    //charging / charged?
    int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
    
    if(isCharging == true){
        tvCharged.setText("CHARGING");
    }else{
        tvCharged.setText("NOT CHARGING");
    }
    
    //how are we charging
    int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
    boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
    
    if(usbCharge == true){
        tvHowCharging.setText("USB");
    }else{
        tvHowCharging.setText("ELECTRICAL OUTLET");
    }
    
    //get battery level and print it out
    int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    tvLevelOutput.setText(level + " / 100");
    pbLevel.setProgress(level);
    pbLevel.invalidate();
    
    //get battery temperatur
    int temp = batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
    tvTempOutput.setText(temp + "Grad");
    pbTemp.incrementProgressBy(temp);
    pbTemp.invalidate();
    
    //get battery voltage
    int voltage = batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
    tvVoltageOutput.setText(voltage + " V");
    pbVoltage.incrementProgressBy(voltage);
    pbVoltage.invalidate();
    
    0 讨论(0)
  • 2020-12-31 23:51

    The same thing happened to me once and I received the broadcast several times.
    This sometimes happens if we register the same broadcast several times and we do not free it by re-registering it.
    Make sure you don't call twice to register the broadcast.

    0 讨论(0)
  • 2021-01-01 00:01

    BroadcastReceiver receives charging state. That's why continuously triggering toast message.

     boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                    status == BatteryManager.BATTERY_STATUS_FULL
    

    instead of

      boolean isCharging =status= BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
    

    please refer this link: Check if device is plugged in

    0 讨论(0)
  • 2021-01-01 00:02
      private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context arg0, Intent intent) {
          // TODO Auto-generated method stub
            //this will give you battery current status
    
        try{
          int level = intent.getIntExtra("level", 0);
          int temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
          int voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
          int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    
          String BStatus = "No Data";
          if (status == BatteryManager.BATTERY_STATUS_CHARGING){BStatus = "Charging";}
          if (status == BatteryManager.BATTERY_STATUS_DISCHARGING){BStatus = "Discharging";}
          if (status == BatteryManager.BATTERY_STATUS_FULL){BStatus = "Full";}
          if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING){BStatus = "Not Charging";}
          if (status == BatteryManager.BATTERY_STATUS_UNKNOWN){BStatus = "Unknown";}
    
          int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
          String BattPowerSource = "No Data";
          if (chargePlug == BatteryManager.BATTERY_PLUGGED_AC){BattPowerSource = "AC";}
          if (chargePlug == BatteryManager.BATTERY_PLUGGED_USB){BattPowerSource = "USB";}
    
          String BattLevel = String.valueOf(level);
    
          int BHealth = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, -1);
          String BatteryHealth = "No Data";
          if (BHealth == BatteryManager.BATTERY_HEALTH_COLD){BatteryHealth = "Cold";}
          if (BHealth == BatteryManager.BATTERY_HEALTH_DEAD){BatteryHealth = "Dead";}
          if (BHealth == BatteryManager.BATTERY_HEALTH_GOOD){BatteryHealth = "Good";}
          if (BHealth == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE){BatteryHealth = "Over-Voltage";}
          if (BHealth == BatteryManager.BATTERY_HEALTH_OVERHEAT){BatteryHealth = "Overheat";}
          if (BHealth == BatteryManager.BATTERY_HEALTH_UNKNOWN){BatteryHealth = "Unknown";}
          if (BHealth == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE){BatteryHealth = "Unspecified Failure";}
    
          //Do whatever with the data here
    
    
        } catch (Exception e){
            Log.v(TAG, "Battery Info Error");
        }
        }
      };
    

    You MUST register it dynamically.

    Doing so in a service would probably be a good bet. This is what I've used:

    this.registerReceiver(this.mBatInfoReceiver, 
                      new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    
    0 讨论(0)
  • 2021-01-01 00:08

    register Receiver in Activity OnResume in place of Manifiest take global variable

    boolean isToastShown = false;
    

    and code of receiver is

     if (isCharging){
        if(!isToastShown){
            Toast.makeText(context, "The device is charging", Toast.LENGTH_SHORT).show();
            }
        }else{
            isToastShown = false;
            Toast.makeText(context, "The device is not charging", Toast.LENGTH_SHORT).show();
    
        }
    
    0 讨论(0)
  • 2021-01-01 00:16

    I found a great way to check if the device is charging, or not. Here is the code of the receiver class:

    public class PowerConnectionReceiver extends BroadcastReceiver {
    
        public PowerConnectionReceiver() {
        }
    
        @Override
        public void onReceive(Context context, Intent intent) {
    
            if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
                Toast.makeText(context, "The device is charging", Toast.LENGTH_SHORT).show();
            } else {
                intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED);
                Toast.makeText(context, "The device is not charging", Toast.LENGTH_SHORT).show();
            }
        }
    
    
    }
    

    Registering it on onResume:

    receiver = new PowerConnectionReceiver();
    
        IntentFilter ifilter = new IntentFilter();
        ifilter.addAction(Intent.ACTION_POWER_CONNECTED);
        ifilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        registerReceiver(receiver, ifilter);
    

    Unregistered on onPause:

            unregisterReceiver(receiver);
    

    Works fine!

    0 讨论(0)
提交回复
热议问题