Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

Detect a new Android notification

In the Android app that I'm working on, I'd like to be able to detect when a new status bar notification appears, regardless of if it was caused by my app. To be more specific, I want to count the number of notifications in a given time frame.

Is this even possible, and if so, how?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...