LifeCycleListener.mm 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #include "LifeCycleListener.h"
  2. #define DEFINE_NOTIFICATION(name) extern "C" __attribute__((visibility ("default"))) NSString* const name = @#name;
  3. DEFINE_NOTIFICATION(kUnityDidUnload);
  4. DEFINE_NOTIFICATION(kUnityDidQuit);
  5. void UnityRegisterLifeCycleListener(id<LifeCycleListener> obj)
  6. {
  7. #define REGISTER_SELECTOR(sel, notif_name) \
  8. if([obj respondsToSelector:sel]) \
  9. [[NSNotificationCenter defaultCenter] addObserver:obj \
  10. selector:sel \
  11. name:notif_name \
  12. object:nil \
  13. ]; \
  14. REGISTER_SELECTOR(@selector(didFinishLaunching:), UIApplicationDidFinishLaunchingNotification);
  15. REGISTER_SELECTOR(@selector(didBecomeActive:), UIApplicationDidBecomeActiveNotification);
  16. REGISTER_SELECTOR(@selector(willResignActive:), UIApplicationWillResignActiveNotification);
  17. REGISTER_SELECTOR(@selector(didEnterBackground:), UIApplicationDidEnterBackgroundNotification);
  18. REGISTER_SELECTOR(@selector(willEnterForeground:), UIApplicationWillEnterForegroundNotification);
  19. REGISTER_SELECTOR(@selector(willTerminate:), UIApplicationWillTerminateNotification);
  20. REGISTER_SELECTOR(@selector(unityDidUnload:), kUnityDidUnload);
  21. REGISTER_SELECTOR(@selector(unityDidQuit:), kUnityDidQuit);
  22. #undef REGISTER_SELECTOR
  23. }
  24. void UnityUnregisterLifeCycleListener(id<LifeCycleListener> obj)
  25. {
  26. [[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationDidFinishLaunchingNotification object: nil];
  27. [[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationDidBecomeActiveNotification object: nil];
  28. [[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationWillResignActiveNotification object: nil];
  29. [[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationDidEnterBackgroundNotification object: nil];
  30. [[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationWillEnterForegroundNotification object: nil];
  31. [[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationWillTerminateNotification object: nil];
  32. [[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityDidUnload object: nil];
  33. [[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityDidQuit object: nil];
  34. }