Question

I want to add and clear window flag inside a thread but not working. Basically i want my thread to keep the screen on for two seconds and then clear the screen on flag.

Here's my code:

public class WriteCommThread extends Thread {

    private long time=2000;

    public WriteCommThread(float count) {


        time = (long) count;

    }

    public void run() {
        while(connectionUnAbort==true){
            // Lock screen
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            slleep();
            //Unlock screen
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            connectionUnAbort=false;

        }
    }

public void slleep(){
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
        }
}
Was it helpful?

Solution

I solved it after doing research, i am posting the referred link.

Answer Link

Here's my solution to my problem and it worked perfectly. I added these runnable classes in my background thread (run method). And after sleeping i could clear the flag to keep the screen on.

runOnUiThread(new Runnable() {
                 public void run() {

            //stuff that updates ui
                    MainActivity.this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                }
            });

runOnUiThread(new Runnable() {
                 public void run() {

            //stuff that updates ui
                    MainActivity.this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                }
            });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top