Skip to content Skip to sidebar Skip to footer

Run Code Background When Charger Gets Connected

I'm trying to run some code every time the charger gets connected to the device and the app is closed. The only thing I've found is to schedule a job that only can run when the cha

Solution 1:

The BatteryManager broadcasts an action whenever the device is connected or disconnected from power. It's important to receive these events even while your app isn't running—particularly as these events should impact how often you start your app in order to initiate a background update—so you should register a BroadcastReceiver in your manifest to listen for both events by defining the ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED within an intent filter.

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

Within the associated BroadcastReceiver implementation, you can extract the current charging state and method as described in the previous step.

publicclassPowerConnectionReceiverextendsBroadcastReceiver {
    @OverridepublicvoidonReceive(Context context, Intent intent) {
        intstatus= intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        booleanisCharging= status == BatteryManager.BATTERY_STATUS_CHARGING ||
                            status == BatteryManager.BATTERY_STATUS_FULL;

        intchargePlug= intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        booleanusbCharge= chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        booleanacCharge= chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
    }
}

Ref: https://developer.android.com/training/monitoring-device-state/battery-monitoring

Solution 2:

You could use a JobScheduler, and use the setRequiresCharging(boolean requiresCharging) method on the JobInfo.Builder you create.

Solution 3:

Keep running a thread in the background and use this method

publicstaticbooleanisConnected(Context context) {
    Intentintent= context.registerReceiver(null, newIntentFilter(Intent.ACTION_BATTERY_CHANGED));
    intplugged= intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    returnplugged== BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
}

if isConnected() returns true then update the time.

Code reference

Post a Comment for "Run Code Background When Charger Gets Connected"