Run Code Background When Charger Gets Connected
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.
Post a Comment for "Run Code Background When Charger Gets Connected"