title: Watchdog for Android
body: <p>To prevent ANR on Android you could implement a <a href="https://en.wikipedia.org/wiki/Watchdog_timer" rel="nofollow">Watchdog Timer</a> which would require to have another Thread running and waiting for heartbeats. If you expect your App to have a refresh rate of 30FPS, guard for a refresh rate of lower than 15FPS. This covers also the case when you would have potentially an ANR in the future. </p>
  
  <p>If you know the places where the UI might get stuck for a long time, you can build the watchdog to guard against this (skip current frame for example). <strong>If it is to long why are you doing it on the UI?</strong> If the action you are performing refers to redrawing the screen you can not do it somewhere else. </p>
  
  <p>Here I made a simple example of a watchdog.</p>
  
  <pre><code>public class MainActivity extends AppCompatActivity {
  
  int count = 0;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
  
      Thread watchdogThread = new Thread(new Runnable() {
          long lastT = System.currentTimeMillis();
          long lastCount = 0;
          long missed = 0;
  
           @Override
           public void run() {
              while(true){
                   if (System.currentTimeMillis()-lastT&gt;1500){
                       if (count == lastCount){
                           missed++;
                       }
                       lastCount = count;
                       if (missed &gt; 3){
                          Log.e("test", "Error");
                      }
                      lastT = System.currentTimeMillis();
                   }
                   try {
                       Thread.sleep(100);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
           }
          });
          watchdogThread.start();
  
          startCycleUI();
  
      }
  
  private void startCycleUI() {
      //Runs on UI Thread
      long lastT = System.currentTimeMillis();
      while(true){
          if (System.currentTimeMillis()-lastT&gt;1000){
              if (count &lt; 10) {
                  count++;
              }
              lastT = System.currentTimeMillis();
          }
          try {
              Thread.sleep(100);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
  }
  </code></pre>
  
  <p>When you do not know where to look, is there a way you could build a watchdog timer that simply restarts the application? How can this watchdog timer live beyond the application context?</p>