我有一个变量在我的代码说它是“状态”。

我想在应用程序中根据这个变量值显示一些文本。这必须在特定的时间延迟下完成。

这就像,

检查状态变量值 显示一些文本 等待10秒 检查状态变量值 显示一些文本 等待15秒

等等。时间延迟可能会有所不同,在文本显示时设置。

我试过Thread。睡眠(时间延迟),它失败。还有更好的办法吗?


当前回答

使用kotlin和它的协程非常简单,首先在你的类中声明一个作业(最好是在你的viewModel中),像这样:

private var repeatableJob: Job? = null

然后当你想要创建并启动它时,这样做:

repeatableJob = viewModelScope.launch {
    while (isActive) {
         delay(5_000)
         loadAlbums(iImageAPI, titleHeader, true)
    }
}
repeatableJob?.start()

如果你想结束它:

repeatableJob?.cancel()

PS: viewModelScope仅在视图模型中可用,你可以使用其他协程作用域,如withContext(Dispatchers.IO)

更多信息:点击这里

其他回答

对任何感兴趣的人来说,这里是我用inazaruk的代码创建的一个类,它创建了所需的一切(我称之为UIUpdater,因为我用它定期更新UI,但你可以叫它任何你喜欢的名字):

import android.os.Handler;
/**
 * A class used to perform periodical updates,
 * specified inside a runnable object. An update interval
 * may be specified (otherwise, the class will perform the 
 * update every 2 seconds).
 * 
 * @author Carlos Simões
 */
public class UIUpdater {
        // Create a Handler that uses the Main Looper to run in
        private Handler mHandler = new Handler(Looper.getMainLooper());

        private Runnable mStatusChecker;
        private int UPDATE_INTERVAL = 2000;

        /**
         * Creates an UIUpdater object, that can be used to
         * perform UIUpdates on a specified time interval.
         * 
         * @param uiUpdater A runnable containing the update routine.
         */
        public UIUpdater(final Runnable uiUpdater) {
            mStatusChecker = new Runnable() {
                @Override
                public void run() {
                    // Run the passed runnable
                    uiUpdater.run();
                    // Re-run it after the update interval
                    mHandler.postDelayed(this, UPDATE_INTERVAL);
                }
            };
        }

        /**
         * The same as the default constructor, but specifying the
         * intended update interval.
         * 
         * @param uiUpdater A runnable containing the update routine.
         * @param interval  The interval over which the routine
         *                  should run (milliseconds).
         */
        public UIUpdater(Runnable uiUpdater, int interval){
            UPDATE_INTERVAL = interval;
            this(uiUpdater);
        }

        /**
         * Starts the periodical update routine (mStatusChecker 
         * adds the callback to the handler).
         */
        public synchronized void startUpdates(){
            mStatusChecker.run();
        }

        /**
         * Stops the periodical update routine from running,
         * by removing the callback.
         */
        public synchronized void stopUpdates(){
            mHandler.removeCallbacks(mStatusChecker);
        }
}

然后你可以在你的类中创建一个UIUpdater对象,并像这样使用它:

...
mUIUpdater = new UIUpdater(new Runnable() {
         @Override 
         public void run() {
            // do stuff ...
         }
    });

// Start updates
mUIUpdater.startUpdates();

// Stop updates
mUIUpdater.stopUpdates();
...

如果你想使用它作为一个活动更新器,把开始调用放在onResume()方法中,停止调用放在onPause()中,这样更新就会根据活动可见性开始和停止。

定时器工作正常。在这里,我使用定时器搜索1.5s后的文本和更新UI。希望这能有所帮助。

private Timer _timer = new Timer();

_timer.schedule(new TimerTask() {
    @Override
    public void run() {
        // use runOnUiThread(Runnable action)
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                search();
            }
        });
    }
}, timeInterval);

在我的例子中,如果以下条件之一为真,我就必须执行一个流程:如果前一个流程已经完成,或者如果5秒已经过去了。所以,我做了以下工作,并且工作得很好:

private Runnable mStatusChecker;
private Handler mHandler;

class {
method() {
  mStatusChecker = new Runnable() {
            int times = 0;
            @Override
            public void run() {
                if (times < 5) {
                    if (process1.isRead()) {
                        executeProcess2();
                    } else {
                        times++;
                        mHandler.postDelayed(mStatusChecker, 1000);
                    }
                } else {
                    executeProcess2();
                }
            }
        };

        mHandler = new Handler();
        startRepeatingTask();
}

    void startRepeatingTask() {
       mStatusChecker.run();
    }

    void stopRepeatingTask() {
        mHandler.removeCallbacks(mStatusChecker);
    }


}

如果process1被读取,它将执行process2。如果不是,则增加变量的时间,并使Handler在一秒钟后执行。它一直保持循环,直到process1被读取或times为5。当times为5时,这意味着5秒过去了,每一秒都执行process1.isRead()的if子句。

有3种方法:

使用ScheduledThreadPoolExecutor

有点多余,因为你不需要一个线程池

   //----------------------SCHEDULER-------------------------
    private final ScheduledThreadPoolExecutor executor_ =
            new ScheduledThreadPoolExecutor(1);
     ScheduledFuture<?> schedulerFuture;
   public void  startScheduler() {
       schedulerFuture=  executor_.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                //DO YOUR THINGS
                pageIndexSwitcher.setVisibility(View.GONE);
            }
        }, 0L, 5*MILLI_SEC,  TimeUnit.MILLISECONDS);
    }


    public void  stopScheduler() {
        pageIndexSwitcher.setVisibility(View.VISIBLE);
        schedulerFuture.cancel(false);
        startScheduler();
    }

使用定时器任务

旧Android风格

    //----------------------TIMER  TASK-------------------------

    private Timer carousalTimer;
    private void startTimer() {
        carousalTimer = new Timer(); // At this line a new Thread will be created
        carousalTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                //DO YOUR THINGS
                pageIndexSwitcher.setVisibility(INVISIBLE);
            }
        }, 0, 5 * MILLI_SEC); // delay
    }

    void stopTimer() {
        carousalTimer.cancel();
    }

使用Handler和Runnable

现代安卓风格

    //----------------------HANDLER-------------------------

    private Handler taskHandler = new android.os.Handler();

    private Runnable repeatativeTaskRunnable = new Runnable() {
        public void run() {
            //DO YOUR THINGS
        }
    };

   void startHandler() {
        taskHandler.postDelayed(repeatativeTaskRunnable, 5 * MILLI_SEC);
    }

    void stopHandler() {
        taskHandler.removeCallbacks(repeatativeTaskRunnable);
    }

无泄漏的处理程序与活动/上下文

在Activity/Fragment类中声明一个不会泄漏内存的内部Handler类

/**
     * 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) {
                // ...
            }
        }
    }

声明一个runnable来执行Activity/Fragment类中的重复任务

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

         //DO YOUR THINGS
        }
    };

在你的Activity/Fragment中初始化Handler对象(这里FlashActivity是我的Activity类)

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

在固定的时间间隔后重复一项任务

taskHandler。postDelayed(repeatativeTaskRunnable, DELAY_MILLIS);

停止重复任务

taskHandler .removeCallbacks(repeatativeTaskRunnable );

更新:在Kotlin:

    //update interval for widget
    override val UPDATE_INTERVAL = 1000L

    //Handler to repeat update
    private val updateWidgetHandler = Handler()

    //runnable to update widget
    private var updateWidgetRunnable: Runnable = Runnable {
        run {
            //Update UI
            updateWidget()
            // Re-run it after the update interval
            updateWidgetHandler.postDelayed(updateWidgetRunnable, UPDATE_INTERVAL)
        }

    }

 // SATART updating in foreground
 override fun onResume() {
        super.onResume()
        updateWidgetHandler.postDelayed(updateWidgetRunnable, UPDATE_INTERVAL)
    }


    // REMOVE callback if app in background
    override fun onPause() {
        super.onPause()
        updateWidgetHandler.removeCallbacks(updateWidgetRunnable);
    }

对于使用Kotlin的人来说,inazaruk的答案将不起作用,IDE将需要初始化变量,因此我们将在一个单独的方法中使用它,而不是在Runnable中使用postDelayed。

Initialize your Runnable like this : private var myRunnable = Runnable { //Do some work //Magic happens here ↓ runDelayedHandler(1000) } Initialize your runDelayedHandler method like this : private fun runDelayedHandler(timeToWait : Long) { if (!keepRunning) { //Stop your handler handler.removeCallbacksAndMessages(null) //Do something here, this acts like onHandlerStop } else { //Keep it running handler.postDelayed(myRunnable, timeToWait) } } As you can see, this approach will make you able to control the lifetime of the task, keeping track of keepRunning and changing it during the lifetime of the application will do the job for you.