简体   繁体   中英

How to kill a Thread when the Home button is pressed

First of all, i know that there are a lot of questions related to this, but i haven´t found what i need.

In almost every answer they said that you should have a running loop in the run() method (which I have) and when you want to kill your Thread you only have to set the boolean condition of the while() to false . I understand that, but in my case every iteration takes a lot of seconds because it´s related to the GUI Thread . Basically, this thread waits until the user presses a button and then it makes more stuff like reproducing some sounds.

So my problem is that it´s impossible to stop the thread setting the boolean to false because it waits for the user, so when the user presses the home button the Thread continues his execution, (waiting for the user´s input) and a few time later (when the user´s time for pressing the button expires) reproduces a sound.

Is there another way to kill the thread in the onStop method or something like that?

Thank you in advance.

@Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();
    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);           
}

Then the following event WILL get fired for home button presses:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {     

    if(keyCode == KeyEvent.KEYCODE_HOME)
    {
       //Thread shutdown
    }
});

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM