Question: I need to perform some periodic tasks as long as an **activity is in the foreground only** (I do not need any processing when the app is asleep). There seem to be two options

1. [Intent Service with Alarm Manager / PendingIntent / BroadcastReceiver](https://github.com/codepath/android_guides/wiki/Starting-Background-Services)
2. ScheduledThreadPoolExecutor

Please provide typical scenarios when either of these should be used, and pros/cons if any.

Answer: 
Handler is way simpler and more efficient when dealing with this.

```
public class MyActivity extends Activity {

   Handler taskHandler;

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInsantsState);
      taskHandler = new Handler();
   }

   @Override
   public void onStart() {
      super.onStart();
      taskHandler.postDelatyed(new TaskRunnable(), 50000);
   }

   @Override
   public void onStop() {
      super.stop();
      taskHandler.removeCallbacksAndMessages(null);
   }

   private class TaskRunnable implements Runnable {
       @Override
       public void run() {
           Log.d("Home", "Heeeyyyyyy I'm typing something!");
           taskHandler.postDelayed(this, 5000);
       }
   }
}

```

If you need a background thread running then you can use HandlerThread.

```
TaskHandlerThread taskThread

// TaskHandler is created in the TaskHandler class instead

public void onStart() {
   super.onStart();
   taskThread = new HandlerThread("TaskHandler");
}

public void onStop(){
   super.onStop();

   taskHandler.removeCallbacksAndMessages(null);
   taskThread.quitSafely();
}

public class TaskHandlerThread extends HandlerThread { 
   @Override
   void onLooperPrepared() {
       taskHandler = new Handler(getLooper());
       taskHandler.post(new TaskRunnable());
   }
}

```
That depends on whether you want to couple this background process with a specific Activity. `ScheduledThreadPoolExecutor` is technically just a ExecutorService with schedule. It is or should be coupled with Activity lifecycle (e.g stop on onPause, start in onStart). Service is not. It can keep running outside the Activity or even Application scope. Any Activity can communicate with it through `ResultReceiver`.