获取系统通知,需要注册一个服务,此服务应设置
android.permission.BIND_NOTIFICATION_LISTENER_SERVICE
权限(此权限是系统权限),添加
android.service.notification.NotificatinListenerService
的过滤器。
<uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" />
<application>
......
<service
android:name=".MyNotificationListenerService"
android:label="@string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
</application>
此服务应继承
NotificationListenerService
,实现onNotificationPosted和onNotificationRemoved方法。
public class MyNotificationListenerService extends NotificationListenerService {
@Override
public IBinder onBind(Intent intent) {
return super.onBind(intent);
}
@Override
public void onCreate() {
super.onCreate();
}
public void onNotificationPosted(StatusBarNotification sbn) {
super.onNotificationPosted(sbn);
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
super.onNotificationRemoved(sbn);
}
}
其中:
- onNotificationPosted(StatusBarNotification sbn) :当系统收到新的通知后出发回调。
- onNotificationRemoved(StatusBarNotification sbn) :当系统通知被删掉后出发回调。
应用安装后,还需要手动开启通知使用权权限,才能正常使用获取系统通知的功能:
版权声明:本文为w2_2015原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。