简体   繁体   中英

Android sleep without thread

How can i make code sleep without threading / runnable. I require to modify layout in a android app, operate a method and reverse layout changes again. However this methods contains counters, whenever i have a inner class, like a runnable timertask or something simular the variable needs to be final, but then i cannot increase the counters.

ChangeLayout();

int round = 0;
while (isPlaying && round < 24){
    round++;
    int specificOccurrence = 0;
    while (isPlaying && specificOccurence < 8) {
        if (somethingSpecific){
            specificOccurence++;
        }
        // operates this while somehow with a 1 second break;
        // after that just continue.
        waitASecondSomehow();
    }
}

ReverseLayoutChanges();

Use a Handler to schedule work on the main thread using postDelayed :

Handler h = new Handler();
h.postDelayed(runnable, delayInMillis);

The runnable above is a Runnable instance that does what you want to execute on the main thread. Keep posting it at each interval, perhaps repeated within the runnable itself to schedule the next iteration.

You should use Timer for this.

    Timer mUiUpdateTimer;
    TimerTask uiUpdateTask; 
    int mistakes=0;
    int periodTime=1000;
    private void createTimeHandler()
    {

        mUiUpdateTimer = new Timer();

        final Handler uiUpdateHandler = new Handler();

        final Runnable uiUpdateRunnable = new Runnable() {

            @Override
            public void run() {
                   // other jobs
                    mistakes++;
            }
        };

        uiUpdateTask = new TimerTask() {

            @Override
            public void run() {
                //for safe UI handling 
                uiUpdateHandler.post(uiUpdateRunnable);

            }
        };

        mUiUpdateTimer.scheduleAtFixedRate(uiUpdateTask, 0, periodTime);


    }

Just Add bellow Handler inside your try block

new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                mistakes++; 
                }
            }

        }, 3000);

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