D
D
Dmitry Donskoy2018-12-24 19:14:55
Java
Dmitry Donskoy, 2018-12-24 19:14:55

How to start a service in the background on Android?

Hello, how to start the service in the background, so that after the application is closed (when it was closed in the list of active applications), it would continue to work? For example, like Vkontakte or any other messenger - the application is not in the list of active applications, but notifications still continue to come (likes, new messages).
Now I use JobScheduler and run it with the setMinimumLatency parameter (after the task is completed, I call the creation of the task again. On Android O, the minimum time to repeat is 15 minutes, I use 30 seconds for tests). If the application is open or hanging in the background, then the service is running. If the application is closed, the function stops working. I tried to execute the code both in the main and in a separate thread using new Thread(new Runnable() in onStartJob
Here is an example of the code used:

package com.example.sentike.myapplication;

import android.app.job.JobParameters;
import android.app.job.JobService;
import android.util.Log;


public class ExampleJobService extends JobService {
    private static final String TAG = "ExampleJobService";
    private boolean jobCancelled = false;

  public static void StartService(Context InContext, Class<?> InServiceClass, long InIntervalInSeconds)
  {
    Log.debug( String.format("[AbstractNotifyPoolService][StartService][InServiceClass: %s / %d]", InServiceClass.getSimpleName(), InServiceClass.hashCode()));

    try {

      //=====================================================
      long InIntervalInMs =  InIntervalInSeconds * 1000;
      Intent ServiceClassIntent = new Intent(InContext, InServiceClass);

      //=====================================================
      ComponentName ServiceComponentName = new ComponentName(InContext.getPackageName(), InServiceClass.getName());

      //=====================================================
      JobScheduler JobSchedulerService = (JobScheduler)InContext.getSystemService(Context.JOB_SCHEDULER_SERVICE);

      //=====================================================
      JobInfo.Builder JobServiceBuilder = new JobInfo.Builder(InServiceClass.hashCode(), ServiceComponentName)
          .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
          .setMinimumLatency(InIntervalInMs)
          .setOverrideDeadline(TimeUnit.SECONDS.toMillis(5))
          .setRequiresDeviceIdle(false)
          .setRequiresCharging(false)
          .setPersisted(true);

      //=====================================================
      int JobServiceScheduleStatus = JobSchedulerService.schedule(JobServiceBuilder.build());

      if(JobServiceScheduleStatus == JobScheduler.RESULT_SUCCESS)
      {
        Log.debug( String.format("[AbstractNotifyPoolService][StartService][InServiceClass: %s][Successfully JobServiceSchedule]", InServiceClass.getSimpleName()));
      }
      else
      {
        Log.debug( String.format("[AbstractNotifyPoolService][StartService][InServiceClass: %s][Failed JobServiceSchedule]", InServiceClass.getSimpleName()));
      }
    }
    catch (Exception e)
    {
      Log.debug( String.format("[AbstractNotifyPoolService][StartService][InServiceClass: %s][Exception: %s]", InServiceClass.getSimpleName(), e.getMessage()));
    }
  }

    @Override
    public boolean onStartJob(JobParameters params) {
        Log.d(TAG, "Job started");
        doBackgroundWork(params);

        return true;
    }

    private void doBackgroundWork(final JobParameters params) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    Log.d(TAG, "run: " + i);
                    if (jobCancelled) {
                        return;
                    }

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                Log.d(TAG, "Job finished");
                jobFinished(params, false);
            }
        }).start();
    }

    @Override
    public void onDestroy()    {
        Log.d(TAG, "onDestroy");
        super.onDestroy();
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        Log.d(TAG, "Job cancelled before completion");
        jobCancelled = true;
        return true;
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GavriKos, 2018-12-24
@GavriKos

You need Service. Services in android are called so.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question