Reputation: 1283
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!
Upvotes: 0
Views: 1938
Reputation: 4159
To avoid freeze UI thread you can implement while in Thread like this [Ref.1]:
public class MyThread extends Thread {
private volatile boolean m_bIsRunning= true;
public void stop() {
bIsRunning= false;
}
public void run() {
while (bIsRunning) {
do_something()
}
}
}
References: this
Upvotes: 2
Reputation: 1704
You can't loop on the UI thread because it doesnt proccess events. Something you can do is make another intent service to do what you want.
Also, instead of using onTouch listeners, you could clean up your code and use this attribute on your button:
android:onClick="onOkTouch"
and then in your activity, have this:
public void onOkTouch(View v, MotionEvent event){
...
}
Upvotes: 2
Reputation: 24722
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.
Upvotes: 3
Reputation: 40347
You can't do continued processing on the UI thread, because android can't make any new calls into the UI thread to deliver more messages until the current method returns.
In this case, the exit of your while loop would only occur is response to a new UI event which can't be delivered until you've concluded the while loop and returned.
Upvotes: 3