Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen and respond to ANR?

Tags:

android

Is there a way to get notified when your app triggers an ANR (Application Not Responding)? Similar to the default exception handler?

In anticipation of the "what would you do with it" answers, just logging. Not "doing" anything.

like image 363
Kevin Galligan Avatar asked Jan 08 '12 20:01

Kevin Galligan


4 Answers

Since the system watchdog does not warn the application, the application itself can have it's own watchdog. The steps are simple, just start a thread that loops doing the following :

  1. Schedule small code to be run on the UI thread as soon as possible.
  2. Wait for X seconds (you decide).
  3. See if the code has run : if it has, go back to 1
  4. If the code has not run, it means that the UI thread has been blocked for at least X seconds, raises an exception with the UI thread stack trace

I have written a small library that does exactly that and that I use with ACRA.

I hope it helps ;)

like image 155
Salomon BRYS Avatar answered Nov 10 '22 03:11

Salomon BRYS


No. Unlike exceptions that occur within your process's VM that you can catch, the ANR is generated by a system watchdog, outside your VM. Google offers info on triggers and avoidance

like image 38
larham1 Avatar answered Nov 10 '22 05:11

larham1


I've been thinking about this quite a bit. You could do the following, although its pretty heavy handed. ANR's write out a threads file to a generally readable directory:

/data/anr/traces.txt

You could have a service, in a different process, poll that file periodically. If the date changes, and your app is at the top, then you probably had an ANR event.

I'm not 100% sure of the format of the file, though.

like image 5
Kevin Galligan Avatar answered Nov 10 '22 04:11

Kevin Galligan


This small ANR-WatchDog thread can help you to monitor your app's thread and get notified when ANR happens.

new ANRWatchDog().setANRListener(new ANRWatchDog.ANRListener() {
    @Override
    public void onAppNotResponding(ANRError error) {
        // Handle the error. For example, log it to HockeyApp:
        ExceptionHandler.saveException(error, new CrashManager());
    }
}).start();
like image 1
Hassan TBT Avatar answered Nov 10 '22 04:11

Hassan TBT