简体   繁体   English

Android:如何在函数运行时停止调用同一函数

[英]Android: how to stop calling the same function while the function is running

example: i got a button, if press it will call a function to fetch data from API to screen. 例如:我有一个按钮,如果按它会调用一个函数,以从API到屏幕获取数据。 but how can i stop calling the function if the user press again and the function is still running(Processing). 但是如果用户再次按下并且该功能仍在运行(处理中),我该如何停止调用该功能。

instead of hiding the button is there any way to handle it? 除了隐藏按钮外,还有什么方法可以处理它? do i need to use thread to handle it? 我需要使用线程来处理吗? to check if thread alive? 检查线程是否还活着? i am not familiar with that. 我对此并不熟悉。 please give me some suggestion and example on how to handle it. 请给我一些有关如何处理它的建议和示例。

sorry for my bad english. 对不起,我的英语不好。 thanks. 谢谢。

Make a boolean that turns true when you press the button. 按下按钮时,使boolean变为true When its true do the normal functions of the method. 如果为真,则执行该方法的正常功能。 Then make it so when the person presses the button again the boolean turns false . 然后,使此人再次按下按钮时, boolean将变为false When it is false make it do what you want to break out or return or do nothing. 当它为假时,使其做您想breakreturn事情,或者什么也不做。

If the function you are calling is synchronized, the you should not have any problem. 如果您正在调用的函数已同步,则您应该没有任何问题。 If the function is starts a thread, then you can do like this: 如果函数是启动线程,则可以这样:

Thread mThrd = null;
public void func() {
    if(mThrd!=null && mThrd.isRunning()) {
        return;
    }

    mThrd = new Thread(/*the runnable that do the job*/);
    mThrd.start();
}

If the function is a framework API that just "does something in the background", it might have some method to tell you that it is done or not, or you can check the result by some methods. 如果函数是一个框架的API,只是“做了在后台”,它可能有一些方法来告诉你,它完成与否,也可以通过一些方法检查结果。 Like: 喜欢:

public void func() {
    if(checkDone()) {
        return;
    }
    callFrameworkAPI();
}

when you call the function, add the following lines to your function, this will make the button unclickable after it has been clicked once. 当您调用该函数时,在函数中添加以下几行,这将使该按钮在单击一次后无法单击。

Button b1 = findViewById(R.id.button_name);
b1.setClickable(false);

After the api fetch is done, probably the end of the function in your case, add the following lines, to make the button clickable again. 在完成api提取之后(可能是函数结束),添加以下几行,以使按钮再次可单击。

b1.setClickable(true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM