我正在使用handler.postDelayed()
在我的应用程序的下一阶段发生之前创建一个等待期。在等待期间,我正在显示一个带有进度条和取消按钮的对话框。
我的问题是我找不到在时间过去之前取消 postDelayed任务的方法。
我正在使用handler.postDelayed()
在我的应用程序的下一阶段发生之前创建一个等待期。在等待期间,我正在显示一个带有进度条和取消按钮的对话框。
我的问题是我找不到在时间过去之前取消 postDelayed任务的方法。
我这样做是为了发布延迟的可运行文件:
myHandler.postDelayed(myRunnable, SPLASH_DISPLAY_LENGTH);
这要删除它:myHandler.removeCallbacks(myRunnable);
如果您确实有多个内部/匿名可运行对象传递给同一个处理程序,并且您想在同一个事件中取消所有使用
handler.removeCallbacksAndMessages(null);
根据文档,
删除所有待处理的回调和发送的消息,其 obj 是令牌。如果 token 为 null,则所有回调和消息都将被删除。
另一种方法是处理 Runnable 本身:
Runnable r = new Runnable {
public void run() {
if (booleanCancelMember != false) {
//do what you need
}
}
}
这很简单,只需使用以下语句,它将取消 Handler 的所有CallBacks并删除Runnable的所有待处理帖子。
handler.removeCallbacksAndMessages(null);
这是一个为延迟操作提供取消方法的类
public class DelayedAction {
private Handler _handler;
private Runnable _runnable;
/**
* Constructor
* @param runnable The runnable
* @param delay The delay (in milli sec) to wait before running the runnable
*/
public DelayedAction(Runnable runnable, long delay) {
_handler = new Handler(Looper.getMainLooper());
_runnable = runnable;
_handler.postDelayed(_runnable, delay);
}
/**
* Cancel a runnable
*/
public void cancel() {
if ( _handler == null || _runnable == null ) {
return;
}
_handler.removeCallbacks(_runnable);
}}
当我通过布尔值传递延迟可运行的帖子中调用 CancelCallBacks(this) 时,它对我有用
Runnable runnable = new Runnable(){
@Override
public void run() {
Log.e("HANDLER", "run: Outside Runnable");
if (IsRecording) {
Log.e("HANDLER", "run: Runnable");
handler.postDelayed(this, 2000);
}else{
handler.removeCallbacks(this);
}
}
};
希望这个要点帮助https://gist.github.com/imammubin/a587192982ff8db221da14d094df6fb4
MainActivity 作为具有处理程序和可运行功能的屏幕启动器,可运行运行到登录页面或带有基本偏好登录用户的提要页面和 firebase。