Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I detect the power button or lock screen button being pressed? When my game is paused in this way, it can cause the game to crash because I need to pause a thread when it happens.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
247 views
Welcome To Ask or Share your Answers For Others

1 Answer

From Christian's answer to this question:

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
        // do what you want with the power button
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

However Jake Basile is right. Unless you have a really good reason for doing something special when the Power Button is pressed, you should be using standard Android life-cycle functions.

When the Power Button is pressed it will call the onPause() method of your application, and when you unlock the device it will call onResume(). This is where you should be managing your thread to prevent the app from crashing.

The documentation on Activity's will give you a detailed description of life-cycle functions, when they are called, and how you should use them. enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...