How can I detect when and how long the charger is plugged? 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. Could you please help me?
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.
At first you need to create correct BroadcastReceiver
that will listen for Battery charging changes. You can create it statically via 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>
Then your Java class must match it's name:
public class BatteryReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// do your stuff
}
}
Or you can create BoadcastReceiver dynamically and you can bound it into Service or Activity (it depends on your needs):
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?
It can be achieved in more possible ways. For sure you need to save somewhere time when charger is connected and disconnected and then substract times:
long chargingTime = endChargingTime - startChargingTime;
And you can use SharedPreferences where you'll save your times (pseudo-code):
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();
}
Hope it'll help to solve your problem you're facing.