How to set Delay for loop in android?

泪湿孤枕 提交于 2019-12-05 15:49:05

Why dont you try what the other is saying with this little effort ;)

public class TestActivity extends Activity{

int value = 0; 
    static int count = 0;
    Handler handle = new Handler();

    StringBuilder sb = new StringBuilder();

    Runnable r  = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            updateTable();
        }
    };

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


               tableButton1.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {       


                value= Integer.parseInt(tableButton1.getText().toString()); 
                updateTable();

            }
       });
      }


     public void updateTable(){

        count+=1000;
        if(count==11000){

            count = 0;
            value=0;
            handle.removeCallbacks(r);
            sb.setLength(0);

        }else{

            sb.append(value + " x " + count/1000 + " = " + count/1000 * value+ "\n");
                        handle.postDelayed(r, 1000);

        }


    }


}
jyomin

Try this

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    public void run() {
        str = tableButton1.getText().toString();  
        a = Integer.parseInt(str);
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 10; i++){
            sb.append(a + " x " + i + " = " + i * a+ "\n");
        }
    }, 5000);
s = String.valueOf(sb);

Intent intent=new Intent(getApplicationContext(),TextViewActivity.class);
intent.putExtra("MA", s);
startActivity(intent);

Add a handler(). Replace your onClick code with:

final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                 str = tableButton1.getText().toString();  
                        a = Integer.parseInt(str);
                        StringBuilder sb = new StringBuilder();
                        for (int i = 1; i <= 10; i++) 
                        {
                            sb.append(a + " x " + i + " = " + i * a+ "\n");

                        }s=String.valueOf(sb);


                        Intent intent=new Intent(getApplicationContext(),TextViewActivity.class);
                        intent.putExtra("MA", s);
                        startActivity(intent);
                     }
    }, 5000);

Repalce 5000 with the time you want it to be delayed for in milliseconds

Add a Handler that will execute your runnable:

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        str = tableButton1.getText().toString();  
        a = Integer.parseInt(str);
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 10; i++){
            sb.append(a + " x " + i + " = " + i * a+ "\n");
//--ADDED stuff here------------------------------------------------------------
            try {
               //Sleep will suspend your Thread for 500 miliseconds and resumes afterwards
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Log.e("error, Thread interrupted", e);
            }
        }
        s = String.valueOf(sb);

        Intent intent=new Intent(getApplicationContext(),TextViewActivity.class);
        intent.putExtra("MA", s);
        startActivity(intent);
    }
Handler handler = new Handler();
//this will execute your runnable after 500 milliseconds
handler.postDelayed(runnable, 500);

You can use that :

public class Scheduler {

// DATA
private OnScheduleTimeListener  mListener;
private Handler                 mHandler;
private int                     mInterval;          // Between each executions
private static final int        DELAY   = 100;      // before first execution
private boolean                 mIsTimerRunning;

public static interface OnScheduleTimeListener {

    public void onScheduleTime();
}

public Scheduler(int interval) {
    super();
    mInterval = interval;
    mHandler = new Handler();
}

private final Runnable  mRunnable   = new Runnable() {

                                        @Override
                                        public void run() {
                                            // Do stuff
                                            mListener.onScheduleTime();
                                            // Repeat
                                            mHandler.postDelayed(mRunnable, mInterval);
                                        }
                                    };

public void setOnScheduleTimeListener(OnScheduleTimeListener listener) {
    mListener = listener;
}

public void startTimer() {
    mIsTimerRunning = true;
    mHandler.postDelayed(mRunnable, DELAY);
}

public void stopTimer() {
    mIsTimerRunning = false;
    mHandler.removeCallbacks(mRunnable);
}

public boolean isTimerRunning() {
    return mIsTimerRunning;
}
}

Now to use it :

private void startTimer() {
        mScheduler = new Scheduler(INTERVAL);
        mScheduler.setOnScheduleTimeListener(new OnScheduleTimeListener() {

        @Override
        public void onScheduleTime() {
                Log.d(TAG, "update");
        });
        mScheduler.startTimer();
}

private void stopTimer(){
    if (mScheduler != null && mScheduler.isTimerRunning()) {
        mScheduler.stopTimer();
        mScheduler = null;
    }
}
Priya Singh

Try this....

    do {
        try {
            try {
                response_req_sequence = SimpleHttpClient
                        .sendresponseSequReqRes(response_send_order);
                System.out.println("response of sequence request"
                        + response_req_sequence);
                System.out.println(" i  ma in thread");
                if (response_req_sequence.trim().length() != 0) {
                    System.out.println("response in result of sequ"+ response_req_sequence);
                    break;
                }
                Thread.sleep(10000);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    } while (response_req_sequence.trim().equalsIgnoreCase(""));

This is working fine for me. you can customize according to you.

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