我有一个变量在我的代码说它是“状态”。
我想在应用程序中根据这个变量值显示一些文本。这必须在特定的时间延迟下完成。
这就像,
检查状态变量值 显示一些文本 等待10秒 检查状态变量值 显示一些文本 等待15秒
等等。时间延迟可能会有所不同,在文本显示时设置。
我试过Thread。睡眠(时间延迟),它失败。还有更好的办法吗?
我有一个变量在我的代码说它是“状态”。
我想在应用程序中根据这个变量值显示一些文本。这必须在特定的时间延迟下完成。
这就像,
检查状态变量值 显示一些文本 等待10秒 检查状态变量值 显示一些文本 等待15秒
等等。时间延迟可能会有所不同,在文本显示时设置。
我试过Thread。睡眠(时间延迟),它失败。还有更好的办法吗?
当前回答
对于使用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.
其他回答
基于上面关于ScheduledThreadPoolExecutor的帖子,我提出了一个适合我的需求的实用程序(想要每3秒触发一个方法):
class MyActivity {
private ScheduledThreadPoolExecutor mDialogDaemon;
private void initDebugButtons() {
Button btnSpawnDialogs = (Button)findViewById(R.id.btn_spawn_dialogs);
btnSpawnDialogs.setVisibility(View.VISIBLE);
btnSpawnDialogs.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
spawnDialogs();
}
});
}
private void spawnDialogs() {
if (mDialogDaemon != null) {
mDialogDaemon.shutdown();
mDialogDaemon = null;
}
mDialogDaemon = new ScheduledThreadPoolExecutor(1);
// This process will execute immediately, then execute every 3 seconds.
mDialogDaemon.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
// Do something worthwhile
}
});
}
}, 0L, 3000L, TimeUnit.MILLISECONDS);
}
}
定时器工作正常。在这里,我使用定时器搜索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);
使用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)
更多信息:点击这里
对于使用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.
对任何感兴趣的人来说,这里是我用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()中,这样更新就会根据活动可见性开始和停止。