简体   繁体   中英

if called Cancel or stop same function then start fresh if presently running in Android

How do I within Android, if a function is called which is already running, cancel/stop that function then start it from the beginning?

My code looks like the below, basically throughout my application a given function( Important(); ) is called but rather than have that function run several times or prevent users from running the function again if presently running. I'd like to Cancel/stop the currently running function, then start it fresh?

How can I go about doing this?

Code:

public void Important() {
//Do lots of stuff
}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Important();
    }

    @Override
    protected void onResume() {
        super.onResume();
    Important();
    }

I've already attempted the below making use of booleans. But it just stops a user from running the function again if already running? (which isn't what I'm trying to do)

I want, when the function is called again. The running function is stopped. Then freshly executed

Code:

Boolean runningCode = false;
    public void Important() {
if (runningCode== false) { 
runningCode = true;
    //Do lots of stuff
runningCode = false;
    }

FYI

Important() is called many times throughout my application ( in addition to the above ), sometimes whilst Important() is still running. Hence the need for a solution to my question :-)

Tasks like resetting variables and formatting the page are carried out within Important(); , it is not running on a separate thread. These are tasks that need to be completed on the main UI thread

You can use a Handler on the UI thread and post messages or Runnables to it. Make every discrete action in the Important() function be a message or Runnable containing a function (eg, resetVariables() , formatThePage() , etc). Whenever you call the function again, just call removeCallbacksAndMessages on the Handler and it will drop all actions that have not yet been executed.

Well, I don't understand why you want to do something like this?

There is not one simple answer to that. Probably working solution would be something like this

public void Important() {
if (runningCode == false) { 
    runningCode = true;
    //Do lots of stuff
    runningCode = false;
} else {
    // stop current code from execution
    runningCode = false;
    Important();
}

But you must figure your own code to stop current execution as it may result in broken state of objects etc...

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