Search code examples
androidandroid-service

Can a JobScheduler execute a foreground service?


Is it possible? I need to start my foreground service because I'm using it with the UI thread,

Example: Every 25minutes play a video in my app, which is it closed.


Solution

  • I think that this is not the best use case to use JobScheduler, but you can! First of all, you should create

    public class ExerciseJobService extends JobService {
        private Context context;
        public ExerciseJobService(Context context) {
             this.context = context;
        }
    
        @Override
        public boolean onStartJob(JobParameters params) {
            Intent intent = new Intent(context, YOUR_SERVICE.class);
            startForegroundService(intent);
            return true;
       }
    
        @Override
        public boolean onStopJob(JobParameters params) {
            return true;
        }
    }
    

    After that schedule Job

    private FirebaseJobDispatcher jobDispatcher = FirebaseJobDispatcher(GooglePlayDriver(context)) 
    Job myJob = jobDispatcher.newJobBuilder()
                    .setService(ExerciseJobService::class.java)
                    .setTag("SIMPLE_TAG")
                    .setTrigger(Trigger.NOW)
                    .build();
    jobDispatcher.mustSchedule(myJob);