简体   繁体   中英

Exit from doing something every x seconds

Hello everyone I'm trying to stop a method from doing something every 6 seconds once a certain criteria is met. I figured to use finish() but it redirects me back to the previous layout and still shows the toast message every 6 seconds. Here's the run method

protected static final long TIME_DELAY = 6000;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view);

        mHandler.post(updateTextRunnable);
    }

    Runnable updateTextRunnable=new Runnable(){  
        public void run() {       

            if(//Criteria==true){
                     message();
                         finish(); 
                }
                  mHandler.postDelayed(this, TIME_DELAY);  
                 }  
         };  

public void message(){

        Toast.makeText(this, "Found",
                Toast.LENGTH_SHORT).show();
    }

How can I have it once the the criteria is met exit the run but still stay on the same layout

Only invoke your postDeleyed call if the criteria is false (ie add an else statement as below).

if(//Criteria==true){    
    message();   
    finish();  
} else {    
    mHandler.postDelayed(this, TIME_DELAY);   
}

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