Как использовать обработчик для l oop оператора if каждые 20 секунд - PullRequest
1 голос
/ 29 мая 2020

Привет, у меня возникли проблемы с использованием обработчика (я использовал почти каждый отдельный пример в любом потоке о цикле с использованием обработчика) до l oop оператора if, который мне нужно запускать каждые 20 секунд, я очень новичок в java, и, пожалуйста, игнорируйте мои глупые сообщения тоста, может ли кто-нибудь отредактировать его, чтобы он запускал код каждые 20 секунд, заранее спасибо

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();
    }
}

Ответы [ 2 ]

1 голос
/ 29 мая 2020

Вот второй пример:

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 + " ]");
            }
        };
    }
}
0 голосов
/ 29 мая 2020

Что нужно, не совсем понятно. Вот несколько примеров выполнения задач с фиксированными задержками в отдельном потоке. Есть много разных способов написать такой пример; этот пример - лишь один из многих.

Пример 1 Вывод:

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

Пример 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: Starting emitter with a delay of 5s");
        emitterThread.start();
        System.out.println("main: Started emitter");

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

        System.out.println("main: Stopping emitter");

        emitter.requestStop();
        try {
            emitterThread.join();
            System.out.println("main: Stopped emitter");
        } catch ( InterruptedException e ) {
            System.out.println("main: Interrupted waiting for emitter to finish");
        }

    }

    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 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: Count [ " + counter + " ]");
                    counter++;

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

                System.out.println("emitter: Stopped at count [ " + counter + " ]");
            }
        };
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...