Detect a New Android Notification

Detect a new Android notification

Actually, it is possible, I use it in my app.

For Android 4.2 and below:

You need to register an AccessibilityService and make sure the user enables the service.

Example for a service:

public class InstantMessenger extends AccessibilityService {

@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) {
//Do something, eg getting packagename
final String packagename = String.valueOf(event.getPackageName());
}
}

@Override
protected void onServiceConnected() {
if (isInit) {
return;
}
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
info.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED;
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_SPOKEN;
setServiceInfo(info);
isInit = true;
}

@Override
public void onInterrupt() {
isInit = false;
}
}

Example for checking if your Service is activated

For Android 4.3 and above:

Use the Notification Listener API

How to detect when the notification/system bar is opened

Before I big with the implementation, I will give a brief explanation of my (very hacky) logic. When an Activity is no longer visible to the user for any reason, onWindowFocusChanged(..) gets invoked. However, onStop() only gets invoked when the Activity is no longer visible to the user by going to the background. I noticed that when switching Activities, onStop() is always invoked after onWindowFocusChanged(..), so I added a check in onWindowFocusChanged(..) to see if onStop() had already been invoked (with a 1 second delay), and I did this using the static member. Now for the how-to...

You will need a parent Activity that all the Activities in your app extend. In this parent Activity, add this static member:

private static boolean wasOnStopCalledAfterOnWindowFocusChanged;

Then in your onStop() method, add this line, make sure you invoke it BEFORE super.onStop()

@Override
protected void onStop() {
wasOnStopCalledAfterOnWindowFocusChanged = true;
super.onStop();
}

Finally, you need to override onWindowFocusChanged(..) in this parent Activity, and add in the below logic.

@Override
public void onWindowFocusChanged(boolean hasFocus) {
if (!hasFocus) {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
if (!wasOnStopCalledAfterOnWindowFocusChanged) {

// NOTIFICATION BAR IS DOWN...DO STUFF

}
wasOnStopCalledAfterOnWindowFocusChanged = false;
}
}, 1000);
}
}

Detect if notification has been deleted

A very similar question has already been answered here on SO:

Detect a new Android notification

In short, it's possible to detect when a new notification appears, but that's about it. You can't detect when notifications have been dismissed.



Related Topics



Leave a reply



Submit