I need to break my loop from a handler in that loop, but there is a problem :
break cannot be used outside of a loop or a switch
This is my Code :
Handler mHandler = new Handler();
for (int i = 0; i < 10; i++) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (Break)
break;
}
});
}
I can’t use label break also, like this link : Difference between Return and Break statements
You are adding 10 Runnables to be run by the thread the Handler is associated with, then trying to stop the addition after the fact inside the Runnable.
If you want to stop the remaining runnables running at some point then, if as in your code the Runnable is the same then you can add the same runnable 10 times and remove the remaining using removeCallback.
If the Runnables are different, you can either check your flag at the beginning of each run() method and
returnearly, so the runnables are run but don’t do much, or you can cause each Runnable to add the next one to run if the flag is not set.