1. 程式人生 > >Android迴圈執行某一段程式碼

Android迴圈執行某一段程式碼

方法一:Handler.postDelayed實現
1、執行迴圈的函式如下:

private Handler handler = new Handler();   
    private Runnable task = new Runnable() {  
        public void run() {   
            // TODO Auto-generated method stub
                handler.postDelayed(this,5*1000);//設定迴圈時間,此處是5秒
                //需要執行的程式碼
        }   
    };

2、呼叫的程式碼如下:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        handler.postDelayed(task,5000);//延遲呼叫
        handler.post(task);//立即呼叫

    }

方法二:Timer 實現

1.TimerTask例項

    TimerTask timerTask = new TimerTask() {

        @Override
public void run() { Message msg = new Message(); msg.what = 1; handler.sendMessage(msg); } }; Handler handler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case 1: //需要迴圈執行的程式碼
break; default: break; } }; }; ```

2.呼叫方式

mTimer = new Timer();
        //5s響一次 
        mTimer.schedule(timerTask, 0, 5000);

3.onDestroy()處理

protected void onDestroy() {
        super.onDestroy();
        mTimer.cancel();
    };