Android 如何使用 TimerTask 来运行线程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10029831/
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 02:15:20  来源:igfitidea点击:

How do you use a TimerTask to run a thread?

androidmultithreadingtimertimertask

提问by Alex Haycock

I'm struggling to find documentation for the TimerTask function on Android. I need to run a thread at intervals using a TimerTask but have no idea how to go about this. Any advice or examples would be greatly appreciated.

我正在努力寻找 Android 上 TimerTask 函数的文档。我需要使用 TimerTask 每隔一段时间运行一个线程,但不知道如何去做。任何建议或示例将不胜感激。

回答by Alex

I have implemented something like this and it works fine:

我已经实现了这样的东西,它工作正常:

    private Timer mTimer1;
    private TimerTask mTt1;
    private Handler mTimerHandler = new Handler();

    private void stopTimer(){
        if(mTimer1 != null){
            mTimer1.cancel();
            mTimer1.purge();
        }
    }

    private void startTimer(){
        mTimer1 = new Timer();
        mTt1 = new TimerTask() {
            public void run() {
                mTimerHandler.post(new Runnable() {
                    public void run(){
                        //TODO
                    }
                });
            }
        };

        mTimer1.schedule(mTt1, 1, 5000);
    }

回答by Jave

You use a Timer, and that automatically creates a new Thread for you when you schedule a TimerTaskusing any of the schedule-methods.

您使用 a Timer,当您TimerTask使用任何 - 方法安排 a 时,它会自动为您创建一个新线程schedule

Example:

例子:

Timer t = new Timer();
t.schedule(myTimerTask, 1000L);

This creates a Timer running myTimerTaskin a Thread belonging to that Timer once every second.

这将创建一个myTimerTask在属于该 Timer 的线程中运行的Timer 每秒一次。

回答by Kalai Prakash

This is perfect example for timer task.

这是计时器任务的完美示例。

Timer timerObj = new Timer();
TimerTask timerTaskObj = new TimerTask() {
    public void run() {
       //perform your action here
    }
};
timerObj.schedule(timerTaskObj, 0, 15000);