检测新的 Android 通知

发布于 2025-01-07 01:06:50 字数 115 浏览 2 评论 0原文

在我正在开发的 Android 应用程序中,我希望能够检测到何时出现新的状态栏通知,无论它是否是由我的应用程序引起的。更具体地说,我想计算给定时间范围内的通知数量。

这可能吗?如果可能的话,如何实现?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

桃扇骨 2025-01-14 01:06:50

事实上,这是可能的,我在我的应用程序中使用它。

对于 Android 4.2 及以下版本:

您需要注册 AccessibilityService 并确保用户启用该服务。

服务示例:

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;
}
}

检查您是否服务已激活

对于 Android 4.3 及更高版本:

使用 通知监听器API

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

记忆で 2025-01-14 01:06:50

Android 4.3 中新的通知侦听器 API 使您能够执行此操作。

有了这个,就不再需要可访问性黑客了。它还允许您忽略通知。

The new Notification Listener API in Android 4.3 enables you to do this.

With this there is less need for the accessibility hack. It also allows you to dismiss notifications.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文