how to create a PERMANENT background service on android

Rafael Lima picture Rafael Lima · Dec 13, 2018 · Viewed 7.5k times · Source

I'm having a nightmare trying to create a simple background service on android that runs permanently.

This service will be doing some background tasks like pool users social media and show notification so it requires only one user interaction (login) after that should be able to run forever until the end of the days....

but it is not happening

this is my manifest:

<service
        android:name=".service.MyService"
        android:description="@string/serviceDescription"
        android:directBootAware="false"
        android:enabled="true"
        android:exported="false"
        android:icon="@drawable/ic_logo"
        android:label="@string/serviceLabel"/>

I start service on Application onCreate()

    if (MyService.getInstance() == null) {
        Intent intent = new Intent(this, MyService.class);
        startService(intent);
    }

service:

public void onCreate() {
        super.onCreate();
        this.workDone = 0;

        this.workerMap = new HashMap<User.UserData, Worker>(3);
        this.listeners = new HashMap<Worker, Worker.WorkerListener>(3);
        this.usernames = new HashMap<APIFacade, List<String>>(3);

        this.threadPool = Executors.newFixedThreadPool(3);
        INSTANCE = this;

    }

ABSOLUTELLY NOWHERE IN MY CODE I CALL STOPSERVICE NOR STOPSELF

so why i'm getting nullpointerexception in some random situations?

someone even told me to do the bellow code to force android to "restart" service

  @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

can someone please help me... i'm getting really stressed with this problem

my app has over 1000 daily users and around 10% of them "find a way" to make nullpointerexception when using the service

Answer

Cody Caughlan picture Cody Caughlan · Dec 13, 2018

A lot of the internals of background services has changed in Oreo (or was it Nougat?). I'd get familiar with the Android documentation:

https://developer.android.com/about/versions/oreo/background

and

https://developer.android.com/training/best-background

You might want to consider the JobScheduler framework.