简体   繁体   中英

Android Thread Button sleep

For my project, I am trying to execute a Method every 10 seconds when I click a button "A" and it should stop when I click the button again (kind of on/off).

this is what i reached :-/ :

  ButtonA.setOnClickListener(new OnClickListener() {            
            @Override
            public void onClick(View v) {               

                        Handler handler = new Handler(); 
                    handler.postDelayed(new Runnable() { 
                         public void run() { 
                             showCurrentLocation();
                                Methodexecute();

                         } 
                    }, 10000); 
                }

                    }
        });

How can I repeat executing this method every 10 seconds until the button is clicked again?

thanks

Consider using a Timer with a TimerTask, scheduling it every 10 seconds. I hope this will work:

Timer timer = new Timer();
    TimerTask task = new TimerTask() {

        @Override
        public void run() {
            //insert your methods here
        }
    };

    boolean taskIsRunning = false;
    if(taskIsRunning){
        timer.cancel();
        taskIsRunning = false;
    } else {            
        timer.schedule(task, 0, 10000);
        taskIsRunning = true;
    }
handler = new Handler();
ButtonA.setOnClickListener(new OnClickListener() {
    @Override public void onClick(View v) {

            handler.postDelayed(new Runnable() { 
                 public void run() {
                     if(taskIsRunning){
                         showCurrentLocation();
                         Methodexecute();
                         handler.postDelayed(this,10000);
                     }
                 } 
            }, 10000); 
        }
    }
});

In your onClick method you can also toggle the timer task like so:

...
@Override public void onClick(View v) {
     ...
     toggleTask();
     ...
}
...

and then, from Jonathan's code, something like

boolean taskIsRunning = false;
Timer timer;
TimerTask task = new TimerTask() {
    @Override
    public void run() {
        //insert your methods here
    }
};
private void toggleTask() {
    if(taskIsRunning){
        timer.cancel();
        taskIsRunning = false;
    } else {  
        timer = new Timer()          
        timer.schedule(task, 0, 10000);
        taskIsRunning = true;
    }
}

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