-1

我正在尝试编写一段有效的代码,以便当用户打开屏幕时,调用并运行一个事件或一段代码。这也需要在屏幕进入睡眠状态时起作用,并且应该具有取消功能以在用户命令下阻止这种情况发生。任何人都可以提出任何关于如何在android中编码的想法

4

1 回答 1

0

If you want to do something when your Activity become foreground or background you can override onWindowFocusChanged,

public void onWindowFocusChanged(boolean hasFocus){
    if(hasFocus){
        //activity become foreground
    }
    else{
       //activity become background
    }
}

If you want to do something just based on screen state, regardless of your applications activity visible or not than you need to use a BroadcastReceiver but still need a service or activity running on the background check out this question android: broadcast receiver for screen on and screen off

于 2014-05-29T19:20:18.227 回答