Bogdan Samchuk Bogdan Samchuk - 4 months ago 12
Java Question

How to prevent freeze at long operations

In VB.NET i can execute code like this:

Sub Compute(sender Object, e EventArgs) Handle Compute.Click
For i = 0 to IterationLimit
' Do something
Applicaton.DoEvents()
Next
End Sub


One iteration run approximately 50 ms, but whole method run - about 5 minutes. "Appliction.DoEvents()" allow system to correctly refresh form and allow user to perform action (press button Cancel, stroke hotkey etc). How I can something like in java for Android?

Answer

You want to run the code in a thread if you want the UI and other components to remain responsive while it runs.

See this documentation for a very simple and clear example of how to run a method from a thread: https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html

Basically you want to extend the Thread class:

public class MyThread extends Thread {
    public void run() {
        //do some background work
        //put whatever you want your thread to do here
    }
}

And call it like this:

new MyThread().start();
Comments