Android - 每5秒循环一部分代码

时间:2014-02-12 11:02:29

标签: android loops timer timertask handlers

当我按下按钮START并按下STOP按钮时,我想每5秒开始重复两行代码。我尝试使用TimerTask和Handles,但无法弄清楚如何。

public class MainActivity extends Activity {




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


           //final int i;
           final TextView textView = (TextView) findViewById(R.id.textView);
           final Button START_STOP = (Button) findViewById(R.id.START_STOP);
           final ImageView random_note = (ImageView) findViewById(R.id.random_note);
           final int min = 0;
           final int max = 2;
           final Integer[] image = { R.drawable.a0, R.drawable.a1,R.drawable.a2 };



        START_STOP.setTag(1);
        START_STOP.setText("START");


        START_STOP.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
            int status = (Integer) v.getTag();
            if (status ==1) {
                textView.setText("Hello");
                START_STOP.setText("STOP");
                v.setTag(0);

                final Random random = new Random();

                                //************************************************************
                // I would like to loop next 2 lines of code every 5 seconds.//

                                int i = random.nextInt(2 - 0 + 1) + 0;
                random_note.setImageResource(image[i]);

                //************************************************************
                    }

            else
            {
                textView.setText("Bye");
                START_STOP.setText("Let's PLAY!");
                v.setTag(1);
            }


            }
        });     

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


}

4 个答案:

答案 0 :(得分:24)

在其中一个答案中使用CountDownTimer是一种方法。另一种方法是使用Handler和postDelayed方法:

private boolean started = false;
private Handler handler = new Handler();

private Runnable runnable = new Runnable() {        
    @Override
    public void run() {
        final Random random = new Random();
        int i = random.nextInt(2 - 0 + 1) + 0;
        random_note.setImageResource(image[i]);
        if(started) {
            start();
        }
    }
};

public void stop() {
    started = false;
    handler.removeCallbacks(runnable);
}

public void start() {
    started = true;
    handler.postDelayed(runnable, 2000);        
}

以下是使用Timer和TimerTask的示例:

private Timer timer;
private TimerTask timerTask = new TimerTask() {

    @Override
    public void run() {
        final Random random = new Random();
        int i = random.nextInt(2 - 0 + 1) + 0;
        random_note.setImageResource(image[i]);
    }
};

public void start() {
    if(timer != null) {
        return;
    }
    timer = new Timer();
    timer.scheduleAtFixedRate(timerTask, 0, 2000);
}

public void stop() {
    timer.cancel();
    timer = null;
}

答案 1 :(得分:13)

您可以使用CountDownTimer作为以下方法:

private CountDownTimer timer;

timer = new CountDownTimer(5000, 20) {

    @Override
    public void onTick(long millisUntilFinished) {

    }

    @Override
    public void onFinish() {
        try{
            yourMethod();
        }catch(Exception e){
            Log.e("Error", "Error: " + e.toString());
        }
    }
}.start();

然后再次拨打计时器:

public void yourMethod(){
    //do what you want
    timer.start();
}

要取消计时器,您可以拨打timer.cancel();

希望它有所帮助!

答案 2 :(得分:5)

您可以使用RxJava2 / RxAndroid2并创建一个每秒发送一条消息的Observable(或任何您想要的消息),例如伪代码:

Disposable timer = Observable.interval(1000L, TimeUnit.MILLISECONDS)
            .timeInterval()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<Timed<Long>>() {
                @Override
                public void accept(@NonNull Timed<Long> longTimed) throws Exception {               
                    //your code here.
                    Log.d(TAG, new DateTime());
                }
            });

当您想要停止它时,您只需致电:

timer.dispose();

我觉得这段代码比其他选项更具可读性。

答案 3 :(得分:0)

除了提及使用Handler,CountDownTimer和常规Timer之间的差异之外,我还有更多要补充的内容。正如britzl所提到的,CountDownTimer在内部使用Handler,因此这相当于直接使用处理程序。处理程序用于在非常短的时间内运行Ui。一个例子是setText用于文本视图。对于计算密集型任务,处理程序可能会导致延迟。计时器也只能运行短任务,但它不一定只用于UI的东西。对于更复杂的任务,应该使用新的线程。