广播接收器 - 监控电池电量和充电状态

时间:2015-09-16 12:23:03

标签: android broadcastreceiver

我正在尝试制作两个祝酒词:一个是设备充电时,一个是不充电时。 但接收器表现得很疯狂,发送许多祝酒词,并且崩溃了应用程序。 我找不到问题。 日Thnx! 这是主要活动中的接收者:

public class PowerConnectionReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);

        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                status == BatteryManager.BATTERY_STATUS_FULL;
        if (isCharging){
            Toast.makeText(context, "The device is charging", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(context, "The device is not charging", Toast.LENGTH_SHORT).show();

        }

    }
}

这是清单:

<receiver android:name=".view.MainActivity$PowerConnectionReceiver">
        <intent-filter>
            <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
            <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
        </intent-filter>
    </receiver>

7 个答案:

答案 0 :(得分:6)

我找到了检查设备是否正在充电的好方法。 这是接收器类的代码:

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();
        }
    }


}

在onResume上注册:

receiver = new PowerConnectionReceiver();

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

在onPause上取消注册:

        unregisterReceiver(receiver);

工作正常!

答案 1 :(得分:2)

  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");
    }
    }
  };

你必须动态注册它。

在服务中这样做可能是一个不错的选择。这就是我用过的:

this.registerReceiver(this.mBatInfoReceiver, 
                  new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

答案 2 :(得分:1)

您可以使用此代码

  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();

答案 3 :(得分:0)

在Activity OnResume中注册Receiver代替Manifiest  采取全局变量

boolean isToastShown = false;

和接收者的代码是

 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();

    }

答案 4 :(得分:0)

BroadcastReceiver接收充电状态。这就是为什么不断触发toast消息的原因。

$.getJSON('@Url.Action("SelectedVariation")', { mealsAttribute: meals, portionsAttribute: portions, product: product }, function (route) {
    window.location = route.url;
});

而不是

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

请参考此链接: Check if device is plugged in

答案 5 :(得分:0)

如果您不想在活动中使用广播,可以在服务中使用!!

示例:

public class batteryChangeService extends Service {

    private BroadcastReceiver mBatteryStateReceiver = new BroadcastReceiver() {
        @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();
            }
        }
    };


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        IntentFilter ifilter = new IntentFilter();
        ifilter.addAction(Intent.ACTION_POWER_CONNECTED);
        ifilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        registerReceiver(mBatteryStateReceiver, ifilter);
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(mBatteryStateReceiver);
    }


}

在清单中注册服务:

<service
            android:enabled="true"
            android:name="NAME.COMPANY.APPLICATION.batteryChangeService"
            android:exported="true"/>

实际上,您可以在服务中使用任何BroadcastReceiver!

答案 6 :(得分:0)

同一件事发生在我身上,我多次收到广播。
如果我们多次注册相同的广播,而又没有通过重新注册来释放它,则有时会发生这种情况。
确保您不打两次电话就注册广播。