In my android app, let’s say I have 2 buttons, the first button will start the while loop and the second will stop it, and a method do_something() that I will need to execute over and over again continuously.
public void onCreate() {
my_var = true;
ok = (Button)findViewById(R.id.button1);
ok.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
while(my_var) do_something();
}
return true;
}
});
stop = (Button)findViewById(R.id.button2);
stop.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
my_var = false;
}
return true;
}
});
the following is causing my application and my entire phone to just freeze up. Can anyone at a glance tell what I am doing incorrectly? aLogCat isn’t giving me much info.
Any help would be much appreciated!
It freezes because the loop executes on UI thread and UI can’t process events to stop it. Consequently, it can’t be stopped. You must use different thread for such occasion.