Detecting toast messages

JonWillis picture JonWillis · May 18, 2012 · Viewed 7.3k times · Source

I don't think this is possible, as I haven't found anything in the SDK documentation (yet).

But I could do with knowing if its possible to write an application which logs Toast messages. Logging which application showed it and what the message displayed contained.

This is an entirely personal endeavour to create an app which can detect the toast messages. Because something on my phone is creating a toast saying "Sending..." about once per day, and for the life of me I can't track down the offending application (Service class). I thought it might be GMail or Evernote, but there toast messages for sending are slightly different. I'm going for building an app because 1) I don't know if LogCat would show anything, and 2) I don't want to keep my personal/dev phone plugged in to a PC all the time (as the "Sending..." message occurs so infrequently).

Answer

Floern picture Floern · May 19, 2012

It's possible to catch Messages/Notifications with an Accessibility Service, have a look at that.

You can extend the class AccessibilityService and override the method onAccessibilityEvent() to implement something like this:

public void onAccessibilityEvent(AccessibilityEvent event) {
    if (event.getEventType() != AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED)
        return; // event is not a notification

    String sourcePackageName = (String) event.getPackageName();

    Parcelable parcelable = event.getParcelableData();
    if (parcelable instanceof Notification) {
        // Statusbar Notification
    }
    else {
        // something else, e.g. a Toast message
        String log = "Message: " + event.getText().get(0) 
                   + " [Source: " + sourcePackageName + "]";
        // write `log` to file...
    }
}

Note: This didn't work for me on Android 2.2 as it doesn't seem to catch Toasts, but it worked on Android 4.0+.