How to schedule periodic tasks using Job Scheduler in Android

In this android programming source code example, we are going to schedule periodic tasks using Job Scheduler in Android.

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 schedule periodic tasks using Job Scheduler in Android.

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"    tools:context=".WorkManagerAndJobSchedule.WorkManagerAndJobScheduleActivity16">

    <Button
        android:id="@+id/schedule"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:text="Schedule Job"
        android:textAllCaps="false"
        android:textColor="#ffffff"
        android:textSize="19sp"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="10dp"
        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 android.annotation.TargetApi;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class WorkManagerAndJobScheduleActivity16 extends AppCompatActivity {
    private Button schedule;

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

    @TargetApi(Build.VERSION_CODES.N)
    private void startJob(){
        ComponentName componentName = new ComponentName(this, JobScheduler16.class);
        JobInfo jobInfo = new JobInfo.Builder(14, componentName)
                .setRequiresCharging(true)
                .setPeriodic(15 * 60 * 1000, 5 * 60 * 1000)
                .build();
        JobScheduler jobScheduler = (JobScheduler)getSystemService(JOB_SCHEDULER_SERVICE);
        int resultCode = jobScheduler.schedule(jobInfo);
        if(resultCode == JobScheduler.RESULT_SUCCESS){
            Toast.makeText(WorkManagerAndJobScheduleActivity16.this, "Job Schedule",Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(WorkManagerAndJobScheduleActivity16.this, "Job Not Schedule",Toast.LENGTH_LONG).show();
        }

    }
}

JobScheduler16.java

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Context;
import android.os.Build;

import androidx.core.app.NotificationCompat;

public class JobScheduler16 extends JobService {
    @Override
    public boolean onStartJob(JobParameters params) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        showNotification("Inducesmile", "Job finished");
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return false;
    }

    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());
    }
}

AndroidManifest.xml

<service
            android:name=".JobScheduler16"
            android:permission="android.permission.BIND_JOB_SERVICE" />

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.