您的位置:首页 > 移动开发 > Android开发

Android 通过系统使用NotificationListenerService 监听各种Notification的使用方法

2016-03-01 18:24 661 查看
from:http://blog.csdn.net/zpf8861/article/details/38531669

NotificationListenerService是通过系统调起的服务,当有应用发起通知的时候,系统会将通知的动作和信息回调给NotificationListenerService。

在继承NotificationListenerService服务实现自己逻辑之前,需要在配置文件中添加如下代码,获取权限。

[java] view
plain copy

 print?

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

这样,在系统设置中就能找到开启该服务的开关,以miui为例,在设置--安全与隐私--通知读取权限

该服务中有以下两个抽象方法,是需要开发者在使用该服务的时候实现的。

[java] view
plain copy

 print?

public class NotificationCollectorService extends NotificationListenerService {  

  

    @Override  

    public void onNotificationPosted(StatusBarNotification sbn) {  

          

        Log.i("zpf", "open"+"-----"+sbn.toString());  

    }  

  

    @Override  

    public void onNotificationRemoved(StatusBarNotification sbn) {  

        Log.i("zpf", "shut"+"-----"+sbn.toString());  

  

    }  

  

}  

也就是说当系统发现某应用产生通知或者用户删除某通知,都会回调该服务的这两个函数,函数的参数StatusBarNotification包含着该通知的具体信息。

如果是在Android Wear开发中,使用该方法捕获手机的通知,然后同步到手表中,就是使用该服务进行的中转
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: