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

最佳答案

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


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

<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并将其绑定到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);
}



  如何检测充电器何时以及何时插入?


可以以更多可能的方式实现。确保在连接和断开充电器后需要节省一些时间,然后减去以下时间:

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/

10-11 15:05