iphone怎么检测屏幕是否被点亮 (用UIApplication的Delegate)

本文转载至  http://gaohaijun.blog.163.com/blog/static/176698271201161524857373/ 

 
 
问题:那位能说一下怎么能检测到iphone的屏幕现在是否在被点亮的状态,还是被关闭的黑屏状态,
要用那个api ,给点提示 谢谢了。


复制代码
  1. - (void)didTurnOnDisplay;
  2. - (void)didTurnOffDisplay;


没有测试,但是相信可以。

刚刚测试,假如是子类化UIApplication是无法接受到这个方法的。用Objc Runtime的method_exchangeImplementations(method, method)就可以。

以下代码:

UIApplication方面:

 
复制代码
  1. @interface UIApplication (_)
  2. - (void)handleDidTurnOnDisplay;
  3. - (void)handleDidTurnOffDisplay;
  4. @end
  5. @implementation UIApplication (_)
  6. - (void)handleDidTurnOnDisplay
  7. {
  8.     NSLog(@"Did turn on display.");
  9.     //[self handleDidTurnOnDisplay];
  10.     
  11. }
  12. - (void)handleDidTurnOffDisplay
  13. {
  14.     NSLog(@"Did turn off display.");
  15.     //[self handleDidTurnOffDisplay];
  16. }
  17. @end


UIApplicationDelegate:

 
复制代码
  1. - (void)applicationDidFinishLaunching:(UIApplication *)application {    
  2.     
  3.     Method m1 = class_getInstanceMethod([UIApplication class], @selector(didTurnOnDisplay));
  4.     Method m2 = class_getInstanceMethod([UIApplication class], @selector(didTurnOffDisplay));
  5.     
  6.     Method m3 = class_getInstanceMethod([UIApplication class], @selector(handleDidTurnOnDisplay));
  7.     Method m4 = class_getInstanceMethod([UIApplication class], @selector(handleDidTurnOffDisplay));
  8.     
  9.     method_exchangeImplementations(m1, m3);
  10.     method_exchangeImplementations(m2, m4);
  11.     
  12.     [window makeKeyAndVisible];
  13. }
  14. - (void)applicationWillResignActive:(UIApplication *)application
  15. {
  16.     NSLog(@"Application will resign active.");
  17. }
  18. - (void)applicationDidBecomeActive:(UIApplication *)application
  19. {
  20.     NSLog(@"Application did become active.");
  21. }


以上代码在打开后关闭屏幕再打开的条件下输出:

引用

2009-08-17 19:05:37.770 *[380:207] Application did become active.
2009-08-17 19:06:36.370 *[380:207] Did turn off display.
2009-08-17 19:06:36.452 *[380:207] Application will resign active.
2009-08-17 19:06:43.310 *[380:207] Did turn on display.
2009-08-17 19:06:43.415 *[380:207] Application did become active. 


可见这个是方法在delegate的willResignActive和didBecomeActive之前调用。
 
其实屏幕在变黑时, 会通知程序
- (void)applicationWillResignActive:(UIApplication *)application;

而解锁后变亮会触发
- (void)applicationDidBecomeActive:(UIApplication *)application;
 
 
 
 
 
posted @ 2014-04-02 13:50  天牛  阅读(659)  评论(0编辑  收藏  举报