Maxim
Maxim

Reputation: 179

What kind of services should I use for accessing sensors data in background?

I successfully used a service to do a certain task in the foreground. Now, to do it in the background, I'd remove the handler.removeCallbacks method in onDestroy().

But this would also prevents me from stopping the service using stopService(intent).

I saw on the official docs that I should maybe use JobScheduler (as I target API 28).

Here is a more precise indication of my code :

public class MainActivity {
    private Intent intent;    
    onCreate() {
        if (intent == null) {
            intent = new Intent(this, MyService.class);
        }
    }
    startService(intent);
    ... // Then is some code to  stop the service if needed with  stopService(intent)
}
--------------------------------------------------------------
public class myService {
    private Handler handler = null;
    private static Runnable runnable = null;
    @Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    handler = new Handler();
    runnable = new Runnable() {
        @Override
        public void run() {
            System.out.println("Running service times " + i);
            i++;
            handler.postDelayed(runnable, 1000);
        }
    };
    handler.post(runnable);
}

@Override
public void onDestroy() {
    handler.removeCallbacks(runnable);
    super.onDestroy();
}

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

I would like it to run in the background (even if the device is locked) but still being able to disable the service (or JobScheduler?).

What are your suggestions?

Upvotes: 0

Views: 67

Answers (1)

ahmed mahmoud
ahmed mahmoud

Reputation: 192

you can use work manager

or job dispatcher

and there is a lot of options like SyncAdapter, Bound services, Intent Service

you can use one of these options according to your need

Upvotes: 1

Related Questions