我们继承NotificationListenerService类时,可以在onNotificationPosted中接收到系统通知。但是有时开机后第一次接收不到,经过排查发现是没有注册成功,onListenerConnected()没有被回调
这时我们就需要再手动去注册一次,方法如下:
private void registerNotify(){ try { Class clazz = Class.forName("android.service.notification.NotificationListenerService"); Method registerAsSystemService = clazz.getDeclaredMethod("registerAsSystemService", Context.class, ComponentName.class, int.class); registerAsSystemService.invoke(this,this,new ComponentName(getPackageName(), getClass().getCanonicalName()),-1); Log.i(TAG,"registerNotify success"); } catch (Exception e) { e.printStackTrace(); Log.i(TAG,"registerNotify fail1"); } }
private void unregisterNotify(){ try{ Class<?> clsGlobal = Class.forName("android.service.notification.NotificationListenerService"); Method methodGetString = clsGlobal.getDeclaredMethod("jxUnregisterAsSystemService"); methodGetString.setAccessible(true); methodGetString.invoke(null); }catch(Exception e){ e.printStackTrace(); Log.i(TAG,"unregisterNotify fail"); } }