Android service periodically performing tasks in background?

ammar26 picture ammar26 · Jun 25, 2015 · Viewed 10.5k times · Source

I have created an Android Service which I start simply in my activity

Intent i = new Intent();
i.setClassName("com.abc.app", MyService.class.getName());
startService(i);
bindService(i, connection, Context.BIND_AUTO_CREATE);

Then I use onServiceConnected callback to get my service instance, so I can call its functions

public void onServiceConnected(ComponentName name, IBinder boundService) {
            myService = IMyInterface.Stub.asInterface((IBinder) boundService);
        }

I can successfully call the functions and can get the results. But I want my service to perform a task periodically in background (like a function which will be called after every few minutes) I can't call function from my activity because I finish() my activity after starting the service and I want my service to simply run in background and perform a task.

Answer

toshkinl picture toshkinl · Jun 25, 2015

You need to add а TimerTask, see how to do that here