Search code examples
androidmultithreadingservicenullpointerexceptionworker

How to run active worker in background service?


I have a Worker Thread class extends Thread and I add workers in queue in this class.I want to run one worker in background service.This is my service and onStartCommand methods

 protected WorkerThread workerThread;
 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
     if (this.looperThread.isAlive()) {
        this.looperThread.start(); }
    return Service.START_STICKY;
}

and I startService in my MainActivity,but I close the app I got an error like this looperThread.start() Null point Exception .How can I run worker in back service ? Thanks


Solution

  • You need Intent Service. You can put all your code that you want in worker thread inside it. Here is an example

    public class MyService extends IntentService {
        public MyService() {
            super("Cashback IntentService");
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            ....Your code that is to be executed in background goes here
        }
    }