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

这一生的挚爱 提交于 2019-12-08 04:14:03

问题


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();
    }

回答1:


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();
 }



回答2:


Try this:

final int DELAY= 5000;
int count = 0;
String[] msgs = {"one", "two", "three", "four", "five"};
Handler handler = new Handler();
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        if (count < 5) {
            Toast(msgs[count]);
            handler.post(runnable);
        }
        count++;
    }
};

handler.postDelayed(runnable, DELAY);


来源:https://stackoverflow.com/questions/26050410/android-how-to-call-a-method-multiple-times-with-a-delay-between-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!