Search code examples
androidhandlerrunnable

Android how call function after amount of time in loop


I am new in Android programming, I used to program microcontroller, now I need a few assistance from you guys. I want to call two function with delay after each function called repeatedly until the stop button pressed.

btnStart.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //I want perform these series of function repeatedly
                //until stop button pressed
                while(true){
                    bluetoothDisconnect();
                    delay(3000);
                    bluetoothConnect();
                    delay(3000);
                    if(status == true){
                        break;
                    }
                }
            }

        });

        btnStop.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                status = true;

            }

        });

Big Thanks,


Solution

  • Try this:

      btnStart.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
    
                status = false;
    
                Thread t = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        doLoop();
                    }
                });
    
                t.start();
            }
    
        });
    
        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                 status = true;
            }
        });
    

    where

     private void doLoop(){
        do {
            bluetoothDisconnect();
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            bluetoothConnect();
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
        }   while (!status);
    }
    

    and status is a global variable, FALSE by default (declared as boolean status = false) This code works as a simple solution, however I'd suggest you to look at the AsyncTask class: http://developer.android.com/guide/components/processes-and-threads.html