如何读取Android中所有即将到来的通知?是否可以使用广播接收器来监听传入的通知并能够读取通知信息。
首先,您必须在清单文件中声明您要接收通知的意图,以便您可以获得android.permission.BIND_NOTIFICATION_LISTENER_SERVICE
权限。
AndroidManifest.xml:
<service android:name=".NotificationListener"
android:label="@string/service_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
然后创建一个NotificationListenerService
类并覆盖onNotificationPosted
函数。
了解更多信息,请阅读开发者参考文档:https://developer.android.com/reference/android/service/notification/NotificationListenerService.html
还可以查看这个简单的示例应用程序,以获取实现指导:https://github.com/kpbird/NotificationListenerService-Example/
为了获取所有消息,您需要在onNotificationPosted中执行以下操作
if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)){
Parcelable b[] = (Parcelable[]) extras.get(Notification.EXTRA_MESSAGES);
if(b != null){
for (Parcelable tmp : b){
Bundle msgBundle = (Bundle) tmp;
content = content + msgBundle.getString("text") + "\n";
/*Set<String> io = msgBundle.keySet(); // To get the keys available for this bundle*/
}
}
}