Search code examples
androidloopsbackground-process

Run a loop on background in Android


I have a function that reads the content of the Android clipboard every two seconds and communicates all changes with a remote server.

This works fine in the app is opened. But I need to be able to continue to log the clipboard changes after the app has been closed.

So I tried an IntentService but it doesn't appreciate long loops.

How can I run my infinite loop in the background?


Solution

  • IntentService should be used to process single "request", from another application component, at time.

    Use started service which should be more suitable for problem you describe. Started service runs until you manually stops it or until system gets out of resources and kill whole process.

    Use START_STICKY as return from onStartCommand() method to automatically start it again when system kills it.

    If you also start it in BroadcastReceiver with ACTION_BOOT_COMPLETED action service will be started after device boot.