Android PeriodicWorkRequest Issue - android

Workmanager is not launching the worker. I have a debug breakpoint in the worker class. I am not hitting breakpoint. I am following the example provided by WorkManager tutorial. I am not sure where I am going wrong.
I have created following worker class
public class MessageSyncWorker extends Worker {
public MessageSyncWorker(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
#NonNull
#Override
public Result doWork() {
Log.d(MessageSyncWorker.class.getSimpleName(), "In Message Sync Worker");
return Result.success();
}
}
I am enqueuing the work in MainActivity as below
private void CreateWorkRequest() {
Data.Builder dataBuilder = new Data.Builder();
dataBuilder.putString("URI", "http//192.168.1.103:5168/api/sync");
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED).build();
PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(MessageSyncWorker.class, 1, TimeUnit.MINUTES, 3, TimeUnit.MINUTES)
.addTag("MessageSyncWorker")
.setInputData(dataBuilder.build()).build();
WorkManager workManager = WorkManager.getInstance(getApplicationContext());
workManager.enqueue(workRequest);
}

First thing make sure your PeriodicWorkRequest is not created multiple times and you can check with WorkManager.enqueueUniquePeriodicWork method.
You can find more information on WorkManager documentation. The basic is to use WorkManager.enqueueUniquePeriodicWork(String, ExistingPeriodicWorkPolicy, PeriodicWorkRequest) instead of the WorkManager.enqueue(PeriodicWorkRequest) you’re currently using.
Also, if you use PeriodicWorkRequest with interval less than 15 min, you should return Result.retry(), not success or failure.

Related

Work manager class having issue with executing doWork() method

First let me correct please :
Work Manager : The minimum repeat interval that can be defined is 15 minutes (same as the JobScheduler API).
If this is not correct please let me know.
I have created below class for executing periodic work request :
object WorkManagerUtils {
fun syncWorkManager() {
val myConstraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val syncRequest = PeriodicWorkRequest
.Builder(MyWorker::class.java, 20000, TimeUnit.MILLISECONDS)
.setConstraints(myConstraints)
.build()
WorkManager
.getInstance()
.enqueueUniquePeriodicWork(
Constants.WORKER,
ExistingPeriodicWorkPolicy.KEEP,
syncRequest)
}
}
Below is my Worker class. Please check :
class MyWorker(val context: Context, param: WorkerParameters) : Worker(context, param) {
override fun doWork(): Result {
if (isNetworkAvailable(context)) {
callSyncApi()
} else {
WorkManagerUtils.syncWorkManager()
}
return Result.success()
}
private fun callSyncApi() {
ToastUtils.shortToast(0,"This is working")
}
}
Calling this in my Activity as below :
WorkManagerUtils.syncWorkManager()
You can notice that currently I am just displaying toast as my work. I want to check that is this working or not ?
But the toast is not displaying.
Any interval under 15 minutes will be replaced by 15 minutes.
Assuming your ToastUtils.showToast(...) works, I believe work manager chose 15 minutes of interval and the “KEEP” existing work policy prevented rescheduling and testing.
I suggest while testing change the existing work policy to “REPLACE”.
From work manager 1.0.0 source:
public final class PeriodicWorkRequest extends WorkRequest {
...
public static final long MIN_PERIODIC_INTERVAL_MILLIS = 15 * 60 * 1000L; // 15 minutes
...
}
public class WorkSpec {
...
public void setPeriodic(long intervalDuration) {
if (intervalDuration < MIN_PERIODIC_INTERVAL_MILLIS) {
...
IntervalDuration = MIN_PERIODIC_INTERVAL_MILLIS;
}
}
...
}
There is an overload of setPeriodic function which applies the same interval enforcement.

JobScheduler - How to skip first job run of periodic job?

in my app i have set a periodic job that is set to run every 30 minutes.
The first job run occurs right when I do schedule that periodic job, which is not wanted in my case.
What I want is to skip the first run so that it will run for the first time after 30+ minutes.
My two thoughts on how to approach this was to either have it not run at all for the first 30 minutes somehow (some kind of delay), or mark the first job run as done before even having the chance to start.
Unfortunately I have not found any method in JobInfo that would allow me to do any of those.
Another workaround that would fulfill my needs would be to somehow limit the jobs to only occur while app is in the background. It does not entirely solve the issue but it could serve as a workaround in my case.
Following is my current code for scheduling the periodic job:
private void scheduleJob() {
ComponentName componentName = new ComponentName(this, myRecurringTask.class);
JobInfo info = new JobInfo.Builder(JOB_ID, componentName)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.setPeriodic(1800000)
.build();
JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
scheduler.schedule(info);
}
I hope someone has run into the same situation and can help me resolve it... Thank you!
Use WorkManager for scheduling backgound work, see introduction here.
1. Add Dependency:
implementation "androidx.work:work-runtime-ktx:2.4.0"
2. Create Worker Class:
class DataRefresher(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result { //will run on background thread
//your logic
return try {
//your logic
Result.success()
} catch (e: HttpException) {
Result.retry()
}
}
}
3. Create Application Class:
class DevBytesApplication : Application() {
private val backgroundScope = CoroutineScope(Dispatchers.Default) //standard background thread
override fun onCreate() { //called when app launches, same as Activity
super.onCreate()
initWork()
}
private fun initWork() {
backgroundScope.launch { //run in background, not affecting ui
setupDataRefreshingWork()
}
}
#SuppressLint("IdleBatteryChargingConstraints")
private fun setupDataRefreshingWork() {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED) //when using wifi
.setRequiresBatteryNotLow(true)
.setRequiresCharging(true)
.setRequiresDeviceIdle(true) //when not running heavy task
.build()
val repeatingRequest = PeriodicWorkRequestBuilder<DataRefresher>(1, TimeUnit.DAYS) //【15 minutes is minimum!!】
.setConstraints(constraints)
.setInitialDelay(30, TimeUnit.MINUTES) //【initial delay!!】
.build()
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
DataRefresher::class.java.simpleName, //work name
ExistingPeriodicWorkPolicy.KEEP, //if new work comes in with same name, discard it
repeatingRequest
)
}
}
4. Setup AndroidManifest:
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.devbytestest">
<application
android:name=".DevBytesApplication" //【here, must!!!】
...
</application>
</manifest>

Periodic work requests still running even when constraints are not met

I'm using WorkManager API (version 2.4.0) to create simple periodic running tasks. Here is the worker class
class BackupWorker(
context: Context,
workerParams: WorkerParameters
) : CoroutineWorker(context, workerParams) {
override suspend fun doWork(): Result = coroutineScope {
Log.i(TAG, "Starting worker")
makeNotification(
"Preparing worker",
applicationContext
)
sleep() //simulate long running task
for(i in 0..20) {
makeNotification(
"Firing update $i",
applicationContext,
true
)
sleep()
}
makeNotification(
"Worker complete",
applicationContext
)
Log.i(TAG, "Finishing backup worker")
Result.success()
}
}
And the work request is set up as follows
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED)
.setRequiresStorageNotLow(true).build();
PeriodicWorkRequest workRequest =
new PeriodicWorkRequest.Builder(BackupWorker.class,
15, TimeUnit.MINUTES)
.setConstraints(constraints)
.build();
WorkManager.getInstance(context).enqueueUniquePeriodicWork("tag_worker",
ExistingPeriodicWorkPolicy.REPLACE,
workRequest);
The work request is being correctly picked up by the OS. However, if I turn Wi-Fi off whilst running, it doesn't stop and continues to run what's inside doWork() which in fact contradicts the whole purpose of this API.
Is there anything missing here? Any thoughts?

Periodic work requests using Work Manager not repeat the work

I am trying to send notifications every 20 minutes using work manager and it sends only one time once I open the app for the first time and then it will not send a notification again What is the reason
The build.gradle (app)
def work_version = "2.3.4"
implementation "androidx.work:work-runtime:$work_version"
The worker class
public class MyWorker extends Worker {
Context context ;
public MyWorker(Context context, WorkerParameters workerParams) {
super(context, workerParams);
this.context = context ;
}
#NonNull
#Override
public Result doWork() {
NotificationHelper.PrepareNotification(context);
return Result.success();
}
}
Build the Periodic work requests
WorkRequest SendNotification = new PeriodicWorkRequest.Builder(MyWorker.class , 20 , TimeUnit.MINUTES)
.addTag("Notification")
.setInitialDelay(6 , TimeUnit.SECONDS)
.build() ;
WorkManager.getInstance(context).enqueue(SendNotification) ;
You used TimeUnit.SECONDS and set it to 6 seconds.
The minimum duration of the workManager is 15 minutes!

Migrate Android Job into Android Work manager

I have implemented Evernote Android Job in my android application. but i want to change it as WorkManager.
JobManager.create(this).addJobCreator(new MyJob());
public class MyJob implements JobCreator {
#Nullable
#Override
public Job create(#NonNull String tag) {
switch (tag) {
case SyncMasterDataJOB.TAG:
return new SyncMasterDataJOB();
}
return null;
}
}
Job Class:
public class SyncMasterDataJOB extends Job {
public static final String TAG = "job_note_sync";
#NonNull
#Override
protected Result onRunJob(#NonNull Params params) {
return Result.SUCCESS;
}
public static void schedulePeriodic() {
try{
new JobRequest.Builder(SyncMasterDataJOB.TAG)
.setPeriodic(15*1000, 5*1000)
.setUpdateCurrent(true)
.build()
.schedule();
} catch (Exception e){
e.printStackTrace();
}
}
How can i change Job into android workmanager.
WorkManager is highly configurable and will allow you to create a PeriodicWorkRequest or a OneTimeWorkRequest these are guaranteed to succeed. PeriodicWorkRequest will fire when you schedule the work, as well as when you have specified in the timer. It will execute in the background even if the app is closed or backgrounded. If you didn't want your task to execute immediately you can use a PWR(PeriodicWorkRequest) with a FlexInterval. See the docs below for more info.
WorkManager Docs
WorkManager Architecture
WorkmManager CodeLab
For example, I created two PeriodicWorkRequests that refresh services and keeps the user logged in always by renewing their token. When the user authenticates the PeriodicWorkRequest is created. In my case, I didn't need it to fire right away as they have just received and cached this information so I utilized the FlexInterval. When the app is backgrounded or closed, the workers continue to refresh services every 12 hours and refresh the token every 6. It works like a charm.
Here is an example:
Build Work:
override fun beginWork() {
val periodicWorkRequest = PeriodicWorkRequest.Builder(
MyWorker::class.java,
REPEAT_INTERVAL, TimeUnit.MINUTES, // How often work should repeat
// Flex not required.
FLEX_INTERVAL, TimeUnit.MINUTES) // Limits execution into a time window
.setConstraints(
Constraints.Builder().setRequiredNetworkType(
NetworkType.CONNECTED).build())
.addTag(MY_WORKER_TAG)
.build()
WorkManager.getInstance().enqueueUniquePeriodicWork(
MY_UNIQUE_WORK,
ExistingPeriodicWorkPolicy.KEEP,
periodicLoginRequest)
Worker:
class MyWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
override fun doWork(): Result {
// DO WORK HERE
Result.success()
} else {
// HANDLE FAILURE HERE
Result.failure()
}
The above is a simple implementation, but it should give you the general idea.

Categories

Resources