简体   繁体   中英

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. 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. 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 . When it is false make it do what you want to break out or return or do nothing.

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. 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.

b1.setClickable(true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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