Introduction to Job Scheduler Android

0
36

Hello, Developers! This is your Android Blogger friend Rishabh Joshi and I’m back with another tutorial.Today we will learn about Job Scheduler. We will do a small project where after some particular time user will see a Toast even if the App is closed or opened. This Toast can be programmatically started and stopped by the user.You can download the APK file or the Project from the Links given above.

Introduction 

Job Scheduler is an API that we can use for scheduling various types of jobs that will be executed in application’s own process. To understand what all jobs can be run and constructed you may refer to this link on JobInfo. We create an object of JobInfo and pass them to JobSchedular to execute our job. For this, we use schedule(JobInfo). where JobInfo is a job that we wish to schedule.

Output 

Download Project – [media-downloader media_id=”2024″]

Download APK – [media-downloader media_id=”2023″]

Wants to Learn Advanced Android Application development from scratch- Beyond Basics

Click Schedule Job to start Service and Cancel All to stop!

Creating New Project  

Step 1: – Creating Project

Open your Android Studio -> Create a new project -> Choose BlankActivity > Finish

Step 2: Creating Layout -> activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/schedule_job"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Schedule Job"/>

    <Button
        android:id="@+id/cancel_all"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cancel All"/>

</LinearLayout>

We will use two Buttons. One for Starting the job and another to stop the Job.

Step 3: Create Service -> JobSchedularService.java

Our class has to extend JobService class. As it is the base class that handles asynchronous requests that were previously scheduled. It executes each incoming job running in your application’s main thread.

package com.mytrendin.jobschedulerapp;

import android.app.job.JobParameters;
import android.app.job.JobService;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

public class JobSchedulerService extends JobService {

    private Handler mJobHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage( Message msg ) {
            Toast.makeText( getApplicationContext(), "Hello There! How are you?", Toast.LENGTH_SHORT ).show();
            jobFinished( (JobParameters) msg.obj, false );
            return true;
        }
    } );

    @Override
    public boolean onStartJob(JobParameters params ) {
        mJobHandler.sendMessage( Message.obtain( mJobHandler, 1, params ) );
        return true;
    }

    @Override
    public boolean onStopJob( JobParameters params ) {
        mJobHandler.removeMessages( 1 );
        return false;
    }

}
  • onStopJob(…): This is called if the system has determined that you must stop the execution of your job even before you’ve had the chance to call.
  • onStartJob(…): We override this method with callback logic of our job.

Related:

15 new cool features introduced in Android Oreo 8.0

Introduction to Collision in Unity

Creating App Introduction(tour) slider with AppIntro Library, using Kotlin

Creating App Introduction(tour) slider using AppIntro Library.

Introduction to Unity

Step 4: Creating MainActivity.java

We will use Builder class for Constructing JobInfo objects.

  JobInfo.Builder builder = new JobInfo.Builder( 1,
                        new ComponentName( getPackageName(), JobSchedulerService.class.getName() ) );
                builder.setPeriodic( 3000 );

builder.setPeriodic(3000) will specify that this job should recur with a provided interval. Only once within this interval. The value provided is in milliseconds.

The following code is responsible for canceling all jobs that have been registered with the JobScheduler by this package.

mCancelAllJobsButton.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick( View v ) {
        mJobScheduler.cancelAll();
    }
});

Your entire code will look like this:

package com.mytrendin.jobschedulerapp;

import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private JobScheduler mJobScheduler;
    private Button mScheduleJobButton;
    private Button mCancelAllJobsButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mJobScheduler = (JobScheduler) getSystemService( Context.JOB_SCHEDULER_SERVICE );
        mScheduleJobButton = (Button) findViewById( R.id.schedule_job );
        mCancelAllJobsButton = (Button) findViewById( R.id.cancel_all );

        mScheduleJobButton.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JobInfo.Builder builder = new JobInfo.Builder( 1,
                        new ComponentName( getPackageName(), JobSchedulerService.class.getName() ) );
                builder.setPeriodic( 3000 );

                if( mJobScheduler.schedule( builder.build() ) <= 0 ) {
                    //If something goes wrong
                }
            }
        });

        mCancelAllJobsButton.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick( View v ) {
                mJobScheduler.cancelAll();
            }
        });
    }
}

Step 5: AndroidManifest.xml

We have used Service to do this Project and Services are application’s components without UI. They are used to implement Long-running background operations. They have to be declared in a Manifest file using <service>. If not declared they will not be seen by the system and will never be run.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mytrendin.jobschedulerapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

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

</manifest>

Conclusion

In this Tutorial, we learned how to implement a JobScheduler to execute any job using Service after a particular Interval. In the case of any queries you can comment below in the comment section and also you can recommend me any topic you want my next blog to be all about. Thank you for reading guys. You can download my Project and APK files from the link above.If You are Beginner Learn Android application development from the scratch


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

LEAVE A REPLY

Please enter your comment!
Please enter your name here