通过NotificationListenerService监听所有通知
通过NotificationListenerService监听所有通知
2015-02-10
当系统收到、移除一个通知(notification)或通知的优先级改变时,系统就会调用NotificationListenerService服务。
要使用这个类,必须在manifest文件中声明android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE权限。例如:
<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>
然后重写onNotificationPosted和onNotificationRemoved两个函数,如果还需要监听通知的优先级改变则重写onNotificationRankingUpdate函数。
NotificationListenerService要求最低API18
public class NotificationListener extends NotificationListenerService { @Override public void onNotificationPosted(StatusBarNotification sbn) { Log.d("NotificationListener", "onNotificationPosted" + sbn.toString()); } @Override public void onNotificationRemoved(StatusBarNotification sbn) { Log.d("NotificationListener", "onNotificationRemoved" + sbn.toString()); } }
程序安装后还需要到系统设置-安全-通知读取权限中授予程序权限