关于NotificationListenerService监听时有失败的处理
-
问题由来
去年进入一家专业做智能穿戴设备的公司,在项目中需要监听系统通知栏变化(主要是IM类app的信息获取到后推送到用户的手环),在继承Android系统提供的NotificationListenerService这个类使用时会出现一个问题:应用进程被杀后再次启动时,服务不生效,导致通知栏有内容变更,服务无法感知 -
解决方法
- 第一种方法是:重启手机,但是用户体验不好
- 第二种方法是:在app每次启动时检测NotificationListenerService是否生效,不生效重新开启
-
代码
public class NotificationCollectorMonitorService extends Service { @Override public void onCreate() { super.onCreate(); ensureCollectorRunning(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } //确认NotificationMonitor是否开启 private void ensureCollectorRunning() { ComponentName collectorComponent = new ComponentName(this, NotificationMonitor.class); ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); boolean collectorRunning = false; List<ActivityManager.RunningServiceInfo> runningServices = manager.getRunningServices(Integer.MAX_VALUE); if (runningServices == null ) { return; } for (ActivityManager.RunningServiceInfo service : runningServices) { if (service.service.equals(collectorComponent)) { if (service.pid == Process.myPid() ) { collectorRunning = true; } } } if (collectorRunning) { return; } toggleNotificationListenerService(); } //重新开启NotificationMonitor private void toggleNotificationListenerService() { ComponentName thisComponent = new ComponentName(this, NotificationMonitor.class); PackageManager pm = getPackageManager(); pm.setComponentEnabledSetting(thisComponent, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); pm.setComponentEnabledSetting(thisComponent, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); } @Override public IBinder onBind(Intent intent) { return null; } }
- 代码说明
- NotificationMonitor为继承NotificationListenerService的具体监听通知的处理类
- 在Application的 onCreate方法中启动NotificationCollectorMonitorService
startService(new Intent(this, NotificationCollectorMonitorService.class))
- 不要忘记了在 AndroidManifest.xml注册此服务
<service android:name=".NotificationCollectorMonitorService"/>