【问题标题】:Broadcast receiver - monitoring the Battery Level and Charging State广播接收器 - 监控电池电量和充电状态
【发布时间】:2015-09-16 12:23:02
【问题描述】:

我正在尝试进行两次祝酒:一次在设备充电时,一次在未充电时。 但是接收者表现得很疯狂,发送了很多祝酒词,并使应用程序崩溃。 我找不到问题。 谢谢! 这是主要活动中的接收者:

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>

【问题讨论】:

  • 请分享 Log cat traces,以便我们可以确定 android 应用程序崩溃的确切问题
  • 无法实例化接收器 com.gidi.places.easymap.view.MainActivity$PowerConnectionReceiver: java.lang.InstantiationException: class com.gidi.places.easymap.view.MainActivity$PowerConnectionReceiver 没有零参数构造函数
  • 在 onResume 中注册接收器,在 OnPause 中取消注册接收器

标签: android broadcastreceiver


【解决方案1】:

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

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

工作正常!

【讨论】:

    【解决方案2】:

    你可以使用这个代码

      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】:

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

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

      而不是

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

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

      【讨论】:

      • 也试过了。 “不充电”的吐司出现了一次,而另一个“正在充电”的吐司却连续出现了三四次……奇怪……
      【解决方案4】:

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

      【讨论】:

      • 谢谢!我像你说的那样注册了它,它不再崩溃了,但我仍然得到了一些祝酒词(四个中的三个)而不是一个......
      • 再次感谢,但它没有t work, the problem is in the receiver itself, i think, because it s 收到许多意图,虽然它不应该...
      【解决方案5】:

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

      例子:

      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】:

        同样的事情发生在我身上一次,我收到了几次广播。
        如果我们多次注册同一个广播并且我们没有通过重新注册来释放它,有时会发生这种情况。
        确保您没有调用两次来注册广播。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多