检查Android的处理程序回调 [英] Check if Android handler has callbacks
问题描述
我有一些code的设置一个计时器,但如果用户设置定时器,而它在使用我需要删除其运行计时器可运行并重新启动。但是,当没有处理程序回调可运行存在且此code被称为崩溃我的应用程序。所以,我需要检查,如果处理程序正在运行,如果是的话结束并重新启动它,但翻翻文件和其他问题#1,我看不出这是可能的。
I have some code which sets a timer, but if a user sets the timer while it is in use I need to remove the runnable which runs the timer and start it again. But when no handler callback runnable exists and this code is called it crashes my application. So I need to check if a handler is running, if so then end it and restart it, but looking through the documentation and other Stackoverflow questions, I cannot see if this is possible.
下面是我的code,我有评论围绕code。如果一个处理器可运行存在,这应该只执行:
Here is my code, I have commented around the code which should only be executed if a handler runnable exists:
submitTimer.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
String s = timer.getText().toString();
if(!s.equals(""))
{
//I NEED TO CHECK A RUNNABLE HANDLER EXISTS AND IF SO THEN RUN THIS CODE, IF NOT IGNORE THIS CODE
Map.handler.removeCallbacks(Map.getRunnable());
Map.runnable.run();
//I NEED TO CHECK A RUNNABLE HANDLER EXISTS AND IF SO THEN RUN THIS CODE, IF NOT IGNORE THIS CODE
int l = Integer.parseInt(s);
Map.timerinmins = l;
timer.setHint("Current Timer is "+Map.timerinmins);
timer.setText("");
Toast.makeText(Preferences.this, "Timer is set!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(Preferences.this, "No value was entered", Toast.LENGTH_SHORT).show();
}
}
});
谁能帮我找出检查处理当前状态的方法是什么?
Can anyone help me figure out a way of checking the handlers current state?
推荐答案
如果你愿意,你可以发送当你第一次把一个回调,然后检查在处理该消息的空消息。这个空消息可能重新present有回调present。删除该邮件后可以再进行类似用于查看是否回调仍然存在。还没有相关的情况,如该由去,但以为我至少会尝试和共享的可能性。
If you want you could send an empty message when you first put a callback in and then check for that message in the handler. This empty message could represent that there is a callback present. Removing that message later could then be used similarly to see if the callback is still there. Don't have a relevant situation such as this to go from, but thought that I would at least try and share a possibility.
...
Map.handler.sendEmptyMessage(CALLBACK_PRESENT_INTEGER);
...
if(Map.handler.hasMessages(CALLBACK_PRESENT_INTEGER)
...
Map.handler.removeMessage(CALLBACK_PRESENT_INTEGER);
...
这可能不是理想的,但可能是一个潜在的解决方案,如果你有从那里回调使用的接入点到您的处理程序。不知道是否有一个直接的方式来了解一下。
This is probably not ideal, but could be a potential solution if you have access to your handler from the point where your callback is used. Not sure if there is a direct way to find out.
这篇关于检查Android的处理程序回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!