如何使用处理程序每隔20秒循环执行一个if语句

huangapple go评论64阅读模式
英文:

How to use a handler to loop an if statement every 20 seconds

问题

Handler handler = new Handler();
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        DisplayManager dm = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);

        for (final Display display : dm.getDisplays()) {
            Toast.makeText(MainActivity.this, "for loop reached", Toast.LENGTH_LONG).show();

            int state = display.getState();
            String StateString = Integer.toString(state);
            Toast.makeText(MainActivity.this, StateString, Toast.LENGTH_LONG).show();

            if (display.getState() == 1) {
                String command = "dumpsys deviceidle force-idle deep";
                try {
                    Process process = Runtime.getRuntime().exec(command);
                } catch (Exception e) {
                    Toast.makeText(MainActivity.this, "failed", Toast.LENGTH_LONG).show();
                }

                //Toast.makeText(MainActivity.this, "not failed yayay", Toast.LENGTH_LONG).show();
                TextView tv9 = (TextView) findViewById(R.id.text_view_id);
                tv9.setText("The screen was turned off");
                Toast.makeText(MainActivity.this, "The screen is offfffffffff lolol", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(MainActivity.this, "The screen is on lolol", Toast.LENGTH_LONG).show();
            }
        }

        handler.postDelayed(this, 20000); // Rerun every 20 seconds
    }
};

handler.post(runnable);
英文:

Hi I have been having issues using the handler (I have used nearly every single example in any thread about looping stuff using handler)to loop a if statement that I need to rerun every 20 secs, I'm very new to java, and please ignore my stupid toast messages, could someone edit it so it will rerun the code every 20 seconds, Thanks in advance

DisplayManager dm = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
for (final Display display : dm.getDisplays()) {
Toast.makeText(MainActivity.this, "for loop reached", Toast.LENGTH_LONG).show();
int state = display.getState();
String StateString = Integer.toString(state);
Toast.makeText(MainActivity.this, StateString, Toast.LENGTH_LONG).show();
if (display.getState() == 1) {
String command = "dumpsys deviceidle force-idle deep";
try {
Process process = Runtime.getRuntime().exec(command);
} catch (Exception e) {
Toast.makeText(MainActivity.this, "failed", Toast.LENGTH_LONG).show();
}
//Toast.makeText(MainActivity.this, "not failed yayay", Toast.LENGTH_LONG).show();
TextView tv9 = (TextView) findViewById(R.id.text_view_id);
tv9.setText("The screen was turned off");
Toast.makeText(MainActivity.this, "The screen is offfffffffff lolol", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "The screen is on lolol", Toast.LENGTH_LONG).show();
}
}

答案1

得分: 1

以下是第二个示例:

package samples;

public class Emitter2 {
    public static final int MS_IN_SEC = 1000;

    public static final int[] DELAYS = { 1, 3, 4, 5, 7 };

    public static void main(String[] args) {

        Emitter[] emitters = new Emitter[DELAYS.length];
        Thread[] emitterThreads = new Thread[DELAYS.length];

        for (int emitterNo = 0; emitterNo < DELAYS.length; emitterNo++) {
            int delay = DELAYS[emitterNo];
            System.out.println("main: Emitter [ " + emitterNo + " ] has delay [ " + delay + " s ]");
            Emitter emitter = newEmitter(MS_IN_SEC * delay);
            emitters[emitterNo] = emitter;
            emitterThreads[emitterNo] = new Thread(emitter);
        }

        System.out.println("main: Starting emitters");
        for (int emitterNo = 0; emitterNo < DELAYS.length; emitterNo++) {
            emitterThreads[emitterNo].start();
        }
        System.out.println("main: Started emitters");

        System.out.println("main: Running emitters for 50s");
        sleep("main", MS_IN_SEC * 50);
        System.out.println("main: Completed running emitters for 50s");

        System.out.println("main: Requesting emitters to stop");
        for (int emitterNo = 0; emitterNo < DELAYS.length; emitterNo++) {
            emitters[emitterNo].requestStop();
        }
        System.out.println("main: Requested emitters to stop");

        System.out.println("main: Waiting for emitters to stop");
        for (int emitterNo = 0; emitterNo < DELAYS.length; emitterNo++) {
            try {
                emitterThreads[emitterNo].join();
            } catch (InterruptedException e) {
                System.out.println("main: Interrupted waiting for emitter to stop");
            }
        }
        System.out.println("main: Waited for emitters to stop");
    }

    public static boolean sleep(String threadName, int mSec) {
        try {
            Thread.sleep(mSec);
        } catch (InterruptedException e) {
            System.out.println(threadName + ": Interrupted on delay of [ " + mSec + " ms ]!");
            return false;
        }
        return true;
    }

    public interface Emitter extends Runnable {
        void requestStop();
        boolean getStopped();
    }

    public static Emitter newEmitter(int delayMs) {
        return new Emitter() {
            private final String emitterName = "emitter" + delayMs;
            private boolean stopped;

            public synchronized void requestStop() {
                stopped = true;
            }

            public synchronized boolean getStopped() {
                return stopped;
            }

            public void run() {
                int counter = 0;
                while (!getStopped()) {
                    System.out.println(emitterName + ": Count [ " + counter + " ]");
                    counter++;

                    if (!sleep(emitterName, delayMs)) {
                        break;
                    }
                }

                System.out.println(emitterName + ": Stopped at count [ " + counter + " ]");
            }
        };
    }
}

注意:代码段中的HTML转义字符已被还原,以及我已经根据你的要求,只返回了翻译的部分。

英文:

Here is a second example:

package samples;
public class Emitter2 {
public static final int MS_IN_SEC = 1000;
public static final int[] DELAYS = { 1, 3, 4, 5, 7 };
public static void main(String[] args) {
Emitter[] emitters = new Emitter[ DELAYS.length ];
Thread[] emitterThreads = new Thread[ DELAYS.length ];
for ( int emitterNo = 0; emitterNo &lt; DELAYS.length; emitterNo++ ) {
int delay = DELAYS[emitterNo];
System.out.println(&quot;main: Emitter [ &quot; + emitterNo + &quot; ] has delay [ &quot; + delay + &quot; s ]&quot;);
Emitter emitter = newEmitter(MS_IN_SEC * delay);
emitters[emitterNo] = emitter;
emitterThreads[emitterNo] = new Thread(emitter);
}
System.out.println(&quot;main: Starting emitters&quot;);
for ( int emitterNo = 0; emitterNo &lt; DELAYS.length; emitterNo++ ) {
emitterThreads[emitterNo].start();
}
System.out.println(&quot;main: Started emitters&quot;);
System.out.println(&quot;main: Running emitters for 50s&quot;);
sleep(&quot;main&quot;, MS_IN_SEC * 50);
System.out.println(&quot;main: Completed running emitters for 50s&quot;);
System.out.println(&quot;main: Requesting emitters to stop&quot;);
for ( int emitterNo = 0; emitterNo &lt; DELAYS.length; emitterNo++ ) {
emitters[emitterNo].requestStop();
}
System.out.println(&quot;main: Requested emitters to stop&quot;);
System.out.println(&quot;main: Waiting for emitters to stop&quot;);
for ( int emitterNo = 0; emitterNo &lt; DELAYS.length; emitterNo++ ) {
try {
emitterThreads[emitterNo].join();
} catch ( InterruptedException e ) {
System.out.println(&quot;main: Interrupted waiting for emitter to stop&quot;);
}
}
System.out.println(&quot;main: Waited for emitters to stop&quot;);
}
public static boolean sleep(String threadName, int mSec) {
try {
Thread.sleep(mSec);
} catch ( InterruptedException e ) {
System.out.println(threadName + &quot;: Interrupted on delay of [ &quot; + mSec + &quot; ms ]!&quot;);
return false;
}
return true;
}
public interface Emitter extends Runnable {
void requestStop();
boolean getStopped();
}
public static Emitter newEmitter(int delayMs) {
return new Emitter() {
private final String emitterName = &quot;emitter&quot; + delayMs;
private boolean stopped;
public synchronized void requestStop() {
stopped= true;
}
public synchronized boolean getStopped() {
return stopped;
}
public void run() {
int counter = 0;
while ( !getStopped() ) {
System.out.println(emitterName + &quot;: Count [ &quot; + counter + &quot; ]&quot;);
counter++;
if ( !sleep(emitterName, delayMs) ) {
break;
}
}
System.out.println(emitterName + &quot;: Stopped at count [ &quot; + counter + &quot; ]&quot;);
}
};
}
}

答案2

得分: 0

以下是翻译好的内容:

你所需要的并不完全清楚。以下是在单独的线程中以固定延迟运行任务的一些示例代码。对于这种类型的示例,有许多不同的编码方式;以下示例仅为众多示例之一。

示例 1 输出:

main: 以 5 秒的延迟启动发射器
main: 已启动发射器
main: 运行发射器 50 秒
emitter: 计数 [ 0 ]
emitter: 计数 [ 1 ]
emitter: 计数 [ 2 ]
emitter: 计数 [ 3 ]
emitter: 计数 [ 4 ]
emitter: 计数 [ 5 ]
emitter: 计数 [ 6 ]
emitter: 计数 [ 7 ]
emitter: 计数 [ 8 ]
emitter: 计数 [ 9 ]
main: 完成运行发射器 50 秒
main: 停止发射器
emitter: 在计数 [ 10 ] 处停止
main: 已停止发射器

示例 1:

package samples;

public class Emitter1 {
    public static final int MS_IN_SEC = 1000;

    public static void main(String[] args) {
        Emitter emitter = newEmitter(MS_IN_SEC * 5);
        Thread emitterThread = new Thread(emitter);
        
        System.out.println("main: 以 5 秒的延迟启动发射器");
        emitterThread.start();
        System.out.println("main: 已启动发射器");

        System.out.println("main: 运行发射器 50 秒");
        sleep("main", MS_IN_SEC * 50);
        System.out.println("main: 完成运行发射器 50 秒");

        System.out.println("main: 停止发射器");

        emitter.requestStop();
        try {
            emitterThread.join();
            System.out.println("main: 已停止发射器");
        } catch ( InterruptedException e ) {
            System.out.println("main: 在等待发射器完成时被中断");
        }

    }

    public static boolean sleep(String threadName, int mSec) {
        try {
            Thread.sleep(mSec);
        } catch ( InterruptedException e ) {
            System.out.println(threadName + ": 在延迟 [ " + mSec + " 毫秒 ] 时被中断!");
            return false;
        }
        return true;
    }

    public interface Emitter extends Runnable {
        void requestStop();
        boolean getStopped();
    }

    public static Emitter newEmitter(int delayMs) {
        return new Emitter() {
            private boolean stopped;

            public synchronized void requestStop() {
                stopped= true;
            }

            public synchronized boolean getStopped() {
                return stopped;
            }

            public void run() {
                int counter = 0;
                while ( !getStopped() ) {
                    System.out.println("emitter: 计数 [ " + counter + " ]");
                    counter++;

                    if ( !sleep("emitter", delayMs) ) {
                        break;
                    }
                }

                System.out.println("emitter: 在计数 [ " + counter + " ] 处停止");
            }
        };
    }
}
英文:

What you need is not entirely clear. Here are some examples of running tasks at fixed delays in a separate thread. There are a lot of different ways to code this sort of example; this example is just one of many.

Example 1 Output:

main: Starting emitter with a delay of 5s
main: Started emitter
main: Running emitter for 50s
emitter: Count [ 0 ]
emitter: Count [ 1 ]
emitter: Count [ 2 ]
emitter: Count [ 3 ]
emitter: Count [ 4 ]
emitter: Count [ 5 ]
emitter: Count [ 6 ]
emitter: Count [ 7 ]
emitter: Count [ 8 ]
emitter: Count [ 9 ]
main: Completed running emitter for 50s
main: Stopping emitter
emitter: Stopped at count [ 10 ]
main: Stopped emitter

Example 1:

package samples;
public class Emitter1 {
public static final int MS_IN_SEC = 1000;
public static void main(String[] args) {
Emitter emitter = newEmitter(MS_IN_SEC * 5);
Thread emitterThread = new Thread(emitter);
System.out.println(&quot;main: Starting emitter with a delay of 5s&quot;);
emitterThread.start();
System.out.println(&quot;main: Started emitter&quot;);
System.out.println(&quot;main: Running emitter for 50s&quot;);
sleep(&quot;main&quot;, MS_IN_SEC * 50);
System.out.println(&quot;main: Completed running emitter for 50s&quot;);
System.out.println(&quot;main: Stopping emitter&quot;);
emitter.requestStop();
try {
emitterThread.join();
System.out.println(&quot;main: Stopped emitter&quot;);
} catch ( InterruptedException e ) {
System.out.println(&quot;main: Interrupted waiting for emitter to finish&quot;);
}
}
public static boolean sleep(String threadName, int mSec) {
try {
Thread.sleep(mSec);
} catch ( InterruptedException e ) {
System.out.println(threadName + &quot;: Interrupted on delay of [ &quot; + mSec + &quot; ms ]!&quot;);
return false;
}
return true;
}
public interface Emitter extends Runnable {
void requestStop();
boolean getStopped();
}
public static Emitter newEmitter(int delayMs) {
return new Emitter() {
private boolean stopped;
public synchronized void requestStop() {
stopped= true;
}
public synchronized boolean getStopped() {
return stopped;
}
public void run() {
int counter = 0;
while ( !getStopped() ) {
System.out.println(&quot;emitter: Count [ &quot; + counter + &quot; ]&quot;);
counter++;
if ( !sleep(&quot;emitter&quot;, delayMs) ) {
break;
}
}
System.out.println(&quot;emitter: Stopped at count [ &quot; + counter + &quot; ]&quot;);
}
};
}
}

huangapple
  • 本文由 发表于 2020年5月29日 20:24:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/62085931.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定