Home » Java » java – How to show toast message using JobScheduler-Exceptionshub

java – How to show toast message using JobScheduler-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have been learning jobscheduler in andorid. I have trying to show a toast message in the onstartjob() after every 1minute. But its not showing up. Any help will be grateful.

jobschedul_service .class:

package com.prajwal.jobscheduler;

import android.app.Service;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class jobschedul_service extends JobService {

    @Override
    public boolean onStartJob(JobParameters jobParameters) {

        Toast.makeText(getApplicationContext(), "After 15 minutes", Toast.LENGTH_SHORT).show();
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        return true;
    }
}

MainActivity.class:

package com.prajwal.jobscheduler;

import androidx.appcompat.app.AppCompatActivity;

import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private static final int LOAD_ARTWORK_JOB_ID = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        JobScheduler jobScheduler =
                (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(new JobInfo.Builder
                (LOAD_ARTWORK_JOB_ID, new ComponentName(this, jobschedul_service.class))
                .setPeriodic(900000)
                .build());
    }
}

Manifest.xml:

  <service
        android:name=".jobschedul_service"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.BIND_JOB_SERVICE"></service>
How to&Answers:

Got the answer!

The reason was the setperiodic(long interval).

As per the ss below:
enter image description here

This function was added in API 21 i.e Lolipop version. Whereas I was running the app on version > Lolipop.

Whereas this new function in the image below:
enter image description here

was added in API 24 i.e. Nougat

Hence, if you are targetting your app below Nougat i.e < Nougat but >= Lolipop then use setPeriodic(long interval) method whereas if u r targetting >= Nougat then use setPeriodic(long interval, long flexinterval).

Solution

 if(Build.VERSION.SDK_INT > Build.VERSION_CODES.N)
        {
            builder.setPeriodic(900000,6000);
        }
        else 
        {
            builder.setPeriodic(900000);
        }