I want to create a job that will be triggered when the device is plugged in, just like broadcast receiver for ACTION_POWER_CONNECTED
.
Here is the worker class:
public class ChargerWorker extends Worker {
/* Constants */
private static final String TAG = "ChargerWorker";
private static final long TRIGGER_AGE = TimeUnit.MINUTES.toMillis(30); // At least 30 min old.
@NonNull
@Override
public Result doWork() {
Log.e(TAG, "Power connection worker of Indoor/Outdoor lib.");
IndoorOutdoorLogger.v(TAG, "Power connection worker of Indoor/Outdoor lib.");
Context context = getApplicationContext();
if (Conditions.isBatteryChargingOnAC(context)) {
IndoorOutdoorLogger.d(context, TAG, "Power plugged and connected to AC.");
Log.e(TAG, "Power plugged and connected to AC.");
if (WiFiConnection.isWifiConnected(context) && WiFiConnection.isCurrentNetworkIndoorRecognized(context)) {
// In this case an "upgrade" to the confidence level is possible.
// Only run when the last known detection is old enough.
DetectionResult latestResult = DetectionResult.loadFromCache(context);
if (!latestResult.isTimestampValid(TRIGGER_AGE)) {
IndoorOutdoorLogger.d(context, TAG, "AC power while connected to a recognized WiFi network, and last detection is old enough, starting detection.");
IndoorOutdoorClient client = new IndoorOutdoorClient(context, null);
client.startShortDetection(Trigger.POWER);
}
}
}
return Result.SUCCESS;
} }
This is how I initialize the work in my onCreate() method:
Constraints constraints = new Constraints.Builder().setRequiresCharging(true).build();
OneTimeWorkRequest simpleReuquest = new OneTimeWorkRequest.Builder(ChargerWorker.class)
.setConstraints(constraints)
.build();
WorkManager.getInstance().enqueue(simpleReuquest);
When I connect the device to the adapter for the first time, everything works as it should. However when I disconnect the device, and try again, I never reach the doWork function again. Instead I see the following message in the logcat:
E/WorkerWrapper: Status for 031e39f1-bc10-4a35-9341-11453fc0ca21 is SUCCEEDED; not doing any work.
Is it because I use OneTimeWorkRequest
? If so how can I schedule it to run every time the device is connected to a power source?