Android在4.3的版本中(即API 18)加入了NotificationListenerService,根据SDK的描述(AndroidDeveloper)可以知道,当系统收到新的通知或者通知被删除时,会触发NotificationListenerService的回调方法。同时在Android 4.4 中新增了Notification.extras 字段,也就是说可以使用NotificationListenerService获取系统通知具体信息,这在以前是需要用反射来实现的。
使用方法:
(1). 新建一个类并继承自NotificationListenerService,override其中重要的两个方法;
public class NotificationMonitor extends NotificationListenerService { @Override public void onNotificationPosted(StatusBarNotification sbn) { Log.i("SevenNLS","Notification posted"); } @Override public void onNotificationRemoved(StatusBarNotification sbn) { Log.i("SevenNLS","Notification removed"); } }
(2). 在AndroidManifest.xml中注册Service并声明相关权限;
<service android:name=".NotificationMonitor" 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>
开启监听功能,需要在系统设置里打开通知读取权限,以下是魅族手机截图:
当然我们在应用中,可以通过 代码直接跳转到 通知开启页面:
private static final String ACTION_NOTIFICATION_LISTENER_SETTINGS = "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"; private void openNotificationAccess() { startActivity(new Intent(ACTION_NOTIFICATION_LISTENER_SETTINGS)); }
那么开启之后,下次就不需要再跳转了,那么如何判断已开启呢?方法如下:
private static boolean isNotificationListenerServiceEnabled(Context context) { Set<String> packageNames = NotificationManagerCompat.getEnabledListenerPackages(context); if (packageNames.contains(context.getPackageName())) { return true; } return false; }
似乎,我们的功能已经完成了。
But
让我们来看一下 开发过程中会遇到的 一些坑:
第一次安装使用这个app,跳转到页面打开通知读取功能,你发现监听通知的发出和删除都没有问题。但你把程序杀掉之后,再次运行,会发现
监听完全不起作用。其实可以说这个是android系统一个bug。
监听服务器并没有开启,原因是没有bindService
那么我们如何去解决这个问题呢
我们需要触发NotificationListenerService的重新绑定, 下面提供一个方法:
private void toggleNotificationListenerService() { PackageManager pm = getPackageManager(); pm.setComponentEnabledSetting(new ComponentName(this, com.xinghui.notificationlistenerservicedemo.NotificationListenerServiceImpl.class), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); pm.setComponentEnabledSetting(new ComponentName(this, com.xinghui.notificationlistenerservicedemo.NotificationListenerServiceImpl.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); }
把应用的NotificationListenerService实现类disable再enable,即可触发系统rebind操作。
这个可以起到重新触发NotificationListenerService重新启动的效果,但会有点小延迟,在10s左右
这个坑的具体问题分析,可以参考这几篇文章:
http://blog.csdn.net/yihongyuelan/article/details/41084165
https://www.zhihu.com/question/33540416
原文地址《Android通知监听NotificationListenerService 使用方法和一些坑》
发表评论