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());
   }
}

```
I think you should use light weight single background thread for the same.

```
Thread thread = new Thread() {
@Override
public void run() {
    try {
        while(true) {

            //put you code here

            sleep(1000);

        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
  }
};

thread.start();

```

after that when activity goes in background some thing like in onStop() method stop this thread using,`thread.stop();`

And if you are going to perform UI related changes then us runOnUiThread. Because you can not perform UI related change from background thread.