gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:42:52 27 4
gpt4 key购买 nike

我正在尝试做两份 toast :一份在设备充电时,另一份在不充电时。但是接收方表现得很疯狂,发送了很多 toast ,并导致应用程序崩溃。我找不到问题所在。谢谢!这是主要 Activity 中的接收器:

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

}

}
}

这是 list :

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

最佳答案

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

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

在暂停时取消注册:

        unregisterReceiver(receiver);

工作正常!

关于android - 广播接收器 - 监控电池电量和充电状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32608505/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com