gpt4 book ai didi

android - 电池充电

转载 作者:行者123 更新时间:2023-11-29 21:08:56 24 4
gpt4 key购买 nike

如何检测充电器插入的时间和时长?我有扩展 BroadcastReceiver 并覆盖 onReceive 的类。我需要检查开始和结束充电以及持续时间,但我不知道从哪里开始。你能帮帮我吗?

最佳答案

I have class which extends BroadcastReceiver and override onReceive. I need to check start and end charging and duration time, but I don't know where to start.

首先,您需要创建正确的BroadcastReceiver将监听电池充电变化。您可以通过 list 静态创建它:

<receiver android:name=".BatteryReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>

然后您的 Java 类必须与其名称相匹配:

public class BatteryReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// do your stuff
}
}

或者您可以动态创建BoadcastReceiver,然后将其绑定(bind)到Service 或Activity 中(这取决于您的需要):

private void registerChargingReceiver() {
if (intentFilter == null) {
intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
}
if (receiver == null) {
receiver = new BroadcastReceiver() {

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

// changer is connected
if (i.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {

// do proper actions
}
// changer is disconneted
if (i.getAction().equals(Intent.ACTION_POWER_DISCONNECTED)) {

// do proper actions
}
}
};
}

// registering receiver
registerReceiver(receiver, intentFilter);
}

How can I detect when and how long the charger is plugged?

它可以通过更多可能的方式实现。当然,当充电器连接和断开时,你需要在某个地方保存时间,然后减去时间:

long chargingTime = endChargingTime - startChargingTime;

你可以使用 SharedPreferences节省时间的地方(伪代码):

if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {

// remove time when charger was diconnected (last before)
prefs.edit().remove("chargingEndTime");

// save time when charged is connected
prefs.edit().putLong("chargingStartTime", System.currentTimeMillis());

prefs.edit().commit();
}

if (intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED)) {

// save time when charger is disconnected
prefs.putLong("chargingEndTime", System.currentTimeMillis()).commit();
}

希望它能帮助解决您面临的问题。

关于android - 电池充电,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23581942/

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