How to check if Android WorkManager has been scheduled already

In this android programming source code example, we are going to check if Android WorkManager has been scheduled already.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to check if Android WorkManager has been scheduled already.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingStart="10dp"
    android:paddingEnd="10dp"    tools:context=".WorkManagerAndJobSchedule.WorkManagerAndJobScheduleActivity5">

    <Button
        android:id="@+id/schedule"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:text="Schedule Work"
        android:textAllCaps="false"
        android:textColor="#ffffff"
        android:textSize="19sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.work.OneTimeWorkRequest;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.common.util.concurrent.ListenableFuture;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class WorkManagerAndJobScheduleActivity5 extends AppCompatActivity {
    private Button schedule;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_manager_and_job_schedule5);
        schedule = (Button) findViewById(R.id.schedule);
        schedule.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startWork();
            }
        });
    }

    private void startWork(){
        if(!isWorkSchedule("Work5")){
            PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(WorkManager5.class, 16, TimeUnit.MINUTES).addTag("Work5").build();;
            WorkManager.getInstance(this).enqueue(periodicWorkRequest);
        }else{
            Toast.makeText(WorkManagerAndJobScheduleActivity5.this, "Work Already Schedule", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean isWorkSchedule(String tag){
        WorkManager instance = WorkManager.getInstance(this);
        ListenableFuture<List<WorkInfo>> statues = instance.getWorkInfosByTag(tag);
        try{
            boolean running = false;
            List<WorkInfo> workInfoList = statues.get();
            for(WorkInfo workInfo : workInfoList){
                WorkInfo.State state = workInfo.getState();
                running = state == WorkInfo.State.RUNNING | state == WorkInfo.State.ENQUEUED;
            }
            return running;
        }catch (ExecutionException e){
            e.printStackTrace();
            return false;
        }catch (InterruptedException e){
            e.printStackTrace();
            return false;
        }
    }
}

WorkManager5.java

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.work.Worker;
import androidx.work.WorkerParameters;


public class WorkManager5 extends Worker {

    public WorkManager5(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        showNotification("Inducesmile", "Hello world, work completed on time");
        return Result.success();
    }

    private void showNotification(String title, String task){
        NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        if(Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){
            NotificationChannel notificationChannel = new NotificationChannel("inducesmile", "inducesmile", NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(notificationChannel);
        }
        NotificationCompat.Builder notification = new NotificationCompat.Builder(getApplicationContext(),"inducesmile")
                .setContentTitle(title)
                .setContentText(task)
                .setSmallIcon(R.mipmap.ic_launcher);
        notificationManager.notify(1, notification.build());
    }
}

app/build.gradle

implementation 'androidx.work:work-runtime:2.1.0-beta02'

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment