Java 如何在android中的固定时间后重复任务?

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

How to repeat a task after a fixed amount of time in android?

javaandroid

提问by user2391890

I want to repeatedly call a method after every 5-seconds and whenever I wish to to stop the repeated call of the method I may stop or restart the repeated call of the method.

我想在每 5 秒后重复调用一个方法,每当我希望停止该方法的重复调用时,我可以停止或重新启动该方法的重复调用。

Here is some sample code that whats really I want to implement. Please help me in this respect I would be very thankful to you.

这是我真正想要实现的一些示例代码。请在这方面帮助我,我将非常感谢你。

private int m_interval = 5000; // 5 seconds by default, can be changed later
private Handler m_handler;

@Override
protected void onCreate(Bundle bundle)
{
  ...
  m_handler = new Handler();
}

Runnable m_statusChecker = new Runnable()
{
     @Override 
     public void run() {
          updateStatus(); //this function can change value of m_interval.
          m_handler.postDelayed(m_statusChecker, m_interval);
     }
};

public void startRepeatingTask()
{
    m_statusChecker.run(); 
}

public void stopRepeatingTask()
{
    m_handler.removeCallbacks(m_statusChecker);
}  

采纳答案by Gru

Set repeated task using this:

使用此设置重复任务:

//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
        //Called each time when 1000 milliseconds (1 second) (the period parameter)
    }

},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);

and if you wanted to cancel the task simply call t.cancel()here tis your Timerobject

如果你想取消任务,只需调用t.cancel()这里t是你的Timer对象

and you can also check comment placed below your answer they have given brief information about that.

您还可以查看答案下方的评论,他们提供了有关该问题的简要信息。

回答by Sanket Kachhela

use TimerTask to call after specific time interval

使用 TimerTask 在特定时间间隔后调用

    Timer timer = new Timer();
    timer.schedule(new UpdateTimeTask(),1, TimeInterval);

and

  class UpdateTimeTask extends TimerTask {

        public void run() 
           {        
            // do stufff
           }

        }

回答by Gazal Patel

Use a Handlerin the onCreate()method. Its postDelayed()method causes the Runnableto be added to the message queue and to be run after the specified amount of time elapses (that is 0 in given example). Then this will queue itself after fixed rate of time (1000 milliseconds in this example).

在方法中使用处理程序onCreate()。它的postDelayed()方法导致Runnable被添加到消息队列并在经过指定的时间量后运行(在给定示例中为 0)。然后这将在固定的时间速率(在本例中为 1000 毫秒)后自行排队。

Refer this code :

请参阅此代码:

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    android.os.Handler customHandler = new android.os.Handler();
    customHandler.postDelayed(updateTimerThread, 0);
}

private Runnable updateTimerThread = new Runnable()
{
    public void run()
    {
        //write here whaterver you want to repeat
        customHandler.postDelayed(this, 1000);
    }
};

回答by Hitesh Sahu

Do it in Android's way with the help of Handler.

Handler的帮助下以 Android 的方式完成。

Declare a Handler which does not leak Memory

声明一个不会泄漏内存的处理程序

/**
     * Instances of static inner classes do not hold an implicit
     * reference to their outer class.
     */
    private static class NonLeakyHandler extends Handler {
        private final WeakReference<FlashActivity> mActivity;

        public NonLeakyHandler(FlashActivity activity) {
            mActivity = new WeakReference<FlashActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            FlashActivity activity = mActivity.get();
            if (activity != null) {
                // ...
            }
        }
    }

Declare a runnable which handle your task

声明一个 runnable 来处理你的任务

   private Runnable repeatativeTaskRunnable = new Runnable() {
        public void run() {
            new Handler(getMainLooper()).post(new Runnable() {
                @Override
                public void run() {

         //DO YOUR THINGS
        }
    };

Initialize handler object in your Activity/Fragment

在您的 Activity/Fragment 中初始化处理程序对象

//Task Handler
private Handler taskHandler = new NonLeakyHandler(FlashActivity.this);

Repeat task after fix time interval

固定时间间隔后重复任务

taskHandler.postDelayed(repeatativeTaskRunnable , DELAY_MILLIS);

taskHandler.postDelayed(repeatativeTaskRunnable, DELAY_MILLIS);

Stop repetition

停止重复

taskHandler .removeCallbacks(repeatativeTaskRunnable );

taskHandler .removeCallbacks(repeatativeTaskRunnable);

回答by Ivan Del Pozo Falconí

You have to put this code inside the activity you want to call every 5 seconds

您必须将此代码放入要每 5 秒调用一次的活动中

final Runnable tarea = new Runnable() {   public void run() {
hola_mundo();//the operation that you want to perform }}; 
ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
timer.scheduleAtFixedRate(tarea, 5, 5, TimeUnit.SECONDS);