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

6

我正在尝试制作两个Toast:一个在设备充电时,另一个在设备未充电时。 但是接收器表现得很疯狂,发送了许多Toast,并导致应用程序崩溃。 我找不到问题所在。 谢谢! 这是MainActivity中的接收器:

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跟踪信息,以便我们可以确定Android应用程序崩溃的确切问题。 - Ashish Agrawal
无法实例化接收器com.gidi.places.easymap.view.MainActivity$PowerConnectionReceiver:java.lang.InstantiationException:类com.gidi.places.easymap.view.MainActivity$PowerConnectionReceiver没有零参数构造函数。 - Gidi Sprintzin
在onResume中注册接收器,而在OnPause中取消注册接收器。 - Ashish Agrawal
6个回答

16

我发现了一种很好的方法来检查设备是否正在充电。

这是接收器类的代码:

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
你可以使用这段代码。
  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
在Activity的OnResume中注册Receiver,而不是在Manifest中注册,使用全局变量。
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();

    }

谢谢!我按照你说的注册了它,现在不会崩溃了,但是我仍然会收到三到四个提示而不是只有一个... - Gidi Sprintzin
再次感谢,但是它没有起作用,问题在于接收器本身,我认为,因为它正在接收一些意图,而不应该... - Gidi Sprintzin

0

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;

请参考此链接: 检查设备是否已插入


我也试过了。 “未充电”提示只出现一次,但“正在充电”的提示会连续出现三到四次……很奇怪…… - Gidi Sprintzin

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"/>

事实上,在服务内部可以使用任何广播接收器!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接