电池充电

时间:2014-05-10 13:59:24

标签: android battery

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

1 个答案:

答案 0 :(得分:2)

  

我有扩展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();
}

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