Android - 每 5 秒循环部分代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21726055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:58:48  来源:igfitidea点击:

Android - loop part of the code every 5 seconds

androidloopstimertimertaskhandlers

提问by Damijan

I would like to start repeating two lines of code every 5 seconds when I press the button START and end it, when I press the button STOP. I was trynig with a TimerTask and Handles, but couldn't figure it out how.

当我按下按钮 START 时,我想每 5 秒开始重复两行代码,当我按下按钮 STOP 时结束它。我正在尝试使用 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;
    }


}

回答by britzl

Using a CountDownTimer as in one of the other answers is one way to do it. Another would be to use a Handler and the postDelayedmethod:

在其他答案之一中使用 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);        
}

Here's an example using a Timer and a TimerTask:

下面是一个使用 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;
}

回答by Giacomoni

You can use CountDownTimeras the following method:

您可以使用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();

And then to call the timer again:

然后再次调用计时器:

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

To cancel the timer, you can call timer.cancel();

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

Hope it helps!

希望能帮助到你!

回答by db80

You can use RxJava2/RxAndroid2 and create an Observable that emits a message every second (or whatever you want), example with pseudo code:

您可以使用 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());
                }
            });

When you want to stop it, you can simply call:

当你想停止它时,你可以简单地调用:

timer.dispose();

I find this code much more readable than the other options.

我发现此代码比其他选项更具可读性。

回答by db80

I don't have much more to add, other than to mention the differences between using Handler, CountDownTimer, and regular Timer. As britzl mentioned, the CountDownTimer uses a Handler internally, so that is equivalent to using the handler directly. A handler is used for running Ui stuff, for very short periods of time. An example would be setText for a text view. For computationally intensive tasks, handlers may cause a lag. A timer also can only run short tasks, but it is not necessarily only for UI stuff. For more complicated tasks, a new Thread should be used.

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