【问题标题】:Battery charging电池充电
【发布时间】:2014-06-28 05:11:52
【问题描述】:

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

【问题讨论】:

  • 看到这个,也许能帮到你:stackoverflow.com/questions/17440729/…
  • 感谢您的回复:) 我可以检查电池是否正在充电,但我无法计算多长时间
  • 您可以在收到充电器插件意图时捕获日期,并在电池充满意图时再次捕获日期,以毫秒为单位获取差异,并从那里获取时间。

标签: android battery


【解决方案1】:

我有扩展 BroadcastReceiver 并覆盖 onReceive 的类。一世 需要检查开始和结束充电和持续时间,但我没有 知道从哪里开始。

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

<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,然后您可以将其绑定到服务或活动中(这取决于您的需要):

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

如何检测充电器的插入时间和时间?

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

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

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

【讨论】:

  • 谢谢!你能告诉我,我的公共类 BatteryReceiver 扩展 BroadcastReceiver 是内部的,所以必须是静态的吗?否则,应用程序停止
  • @user3590445 为什么是inner?为什么不能在单个文件中正常使用?
  • Ok:) 但我不明白如何在 BatteryReceiver 类中创建共享首选项,但我需要在 onReceive 中使用它,对吧?
  • @user3590445 在示例中如何动态创建broadcastReiver。
猜你喜欢
  • 2011-07-29
  • 2019-03-15
  • 1970-01-01
  • 1970-01-01
  • 2011-01-13
  • 1970-01-01
  • 2017-05-15
  • 1970-01-01
  • 2012-07-21
相关资源
最近更新 更多