I created a sample Android application to send requests every 12 hours, I used worker class to achieve this, and I implemented like below, for testing purposes I have changed the time to 6 Sec, but it's not changing every 6 seconds, what went wrong here, Thanks in Advance
MyWorker.class
public class MyWorker extends Worker {
private static final String TAG = "MyWorker";
public MyWorker(@NonNull Context context, @NonNull WorkerParameters params) {
super(context, params);
}
@NonNull
@Override
public Result doWork() {
Log.d(TAG, "doWork: now.... doing it");
sendRequest();
// Do your background work here
// This is where you'll put the code you want to run periodically
return Result.success(); // Indicate success
}
private void sendRequest() {
//send
}
}
in the MainActivity.class inside the onCreate method
private void doWork() {
// Constraints constraints = new Constraints.Builder()
// .setRequiredNetworkType(NetworkType.CONNECTED)
// .build();
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED) // This allows work to run on unmetered networks (Wi-Fi)
.build();
// PeriodicWorkRequest periodicWorkRequest =
// new PeriodicWorkRequest.Builder(MyWorker.class, 12, TimeUnit.HOURS)
// .setConstraints(constraints)
// .build();
PeriodicWorkRequest periodicWorkRequest =
new PeriodicWorkRequest.Builder(MyWorker.class, 6, TimeUnit.SECONDS)
.setConstraints(constraints)
.build();
WorkManager.getInstance(this).enqueue(periodicWorkRequest);
}
Manifest inside the application tag
<service
android:name=".MyWorker"
android:exported="false"
android:permission="android.permission.BIND_JOB_SERVICE" />
Thanks in Advance,