Joolah Joolah - 4 months ago 17
Android Question

Android How to call a method multiple times with a delay between them

I would like to ask, if is there a better away to call a method multiple times giving a 5 sec delay between each call.

But I really want is to call the Toas() method about 7 times, and with my code below, it doesnt look right.

Thanks guys

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...

CallMultipleToast();


........



private void CallMultipleToast(){

Runnable call_1 = new Runnable() {
@Override
public void run() {
Toast("Message one");


Runnable call_2 = new Runnable() {
@Override
public void run() {
Toast("Message two");


Runnable call_3 = new Runnable() {
@Override
public void run() {
Toast("Message three");
//CAN I ADD MORE
}
};//end call_3
new Handler().postDelayed(call_3, 5000);


}
};//end call_2
new Handler().postDelayed(call_2, 5000);

}
};//end call_1
new Handler().postDelayed(call_1, 5000);


}





private void Toast(String message){
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}

Answer

maybe you can do it like this :

private void CallMultipleToast(){
  Thread t = new Thread(){
        @Override
        public void run(){
            try {
                for(i=0;i<7;i++){
                   Toast("Message "+(i+1));
                   sleep(5000);
                }

            } catch (InterruptedException ex) {
                Log.i("error","thread");
            }
        }
    };
   t.start();
 }