1、在AndroidManifest.xml文件中注册服务,确保在
2、编写NotificationListenerService的具体实现,并在其中覆盖以下方法:
public class MyNotificationListenerService extends NotificationListenerService { @Override public void onNotificationPosted(StatusBarNotification sbn) { // 处理通知消息 }
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
    // 处理通知消息被移除
}
}
3、应用程序启动后使用以下代码启动NotificationListenerService服务:
public class MainActivity extends AppCompatActivity { private static final String ENABLED_NOTIFICATION_LISTENERS = "enabled_notification_listeners"; private static final String ACTION_NOTIFICATION_LISTENER_SETTINGS = "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (!isNotificationServiceEnabled()) {
        startActivity(new Intent(ACTION_NOTIFICATION_LISTENER_SETTINGS));
    }
}
private boolean isNotificationServiceEnabled() {
    String pkgName = getPackageName();
    final String flat = Settings.Secure.getString(getContentResolver(), ENABLED_NOTIFICATION_LISTENERS);
    if (!TextUtils.isEmpty(flat)) {
        final String[] names = flat.split(":");
        for (String name : names) {
          final ComponentName cn = ComponentName.unflattenFromString(name);
          if (cn != null) {
              if (TextUtils.equals(pkgName, cn.getPackageName())) {
                  return true;
              }
          }
        }
    }
    return false;
}
}
以上代码将检查是否启用了NotificationListenerService,并在未启用的情况下跳转到通知访问设置页面。