【发布时间】:2016-04-08 16:57:20
【问题描述】:
我正在尝试每秒向 android 中的 stdout 写入一条消息,其中按住给定的按钮(我打算稍后在那里放置一个方法)。我在标准 onTouch 方法中使用 switch 来检测按钮按下:
protected void setFab(FloatingActionButton fab) {
fab.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
System.out.println("Button pressed");
handleButtonDown();
return true;
}
case MotionEvent.ACTION_UP: {
System.out.println("Button released");
handleButtonUp();
return true;
}
default:
return true;
}
}
});
}
和全局两个全局布尔值:
private boolean captureThreadRunning = false;
private boolean cancelCaptureThread = false;
释放按钮时停止循环:
public void handleButtonUp() {
cancelCaptureThread = true;
}
但是,当我启动工作线程时,它会陷入无限循环,即使释放按钮也是如此,因此应该更改全局布尔值:
public void handleButtonDown() {
System.out.println("Capture thread running: " + captureThreadRunning);
if (!captureThreadRunning) {
System.out.println("Thread starting");
startCaptureThread();
}
}
public void startCaptureThread() {
System.out.println("Thread started");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
captureThreadRunning = true;
System.out.println("Got to try");
while (!cancelCaptureThread) {
System.out.println("Success");
try {
System.out.println("Falling asleep");
Thread.sleep(1000);
System.out.println("Slept 1000");
} catch (InterruptedException e) {
throw new RuntimeException(
"Interrupted.", e);
}
}
} finally {
System.out.println("got to finally");
captureThreadRunning = false;
cancelCaptureThread = false;
}
}
});
thread.run();
}
不仅如此,UI 也会被冻结,这当然不应该,因为我在单独的线程中执行所有操作。当我释放按钮时,循环应该停止,因为布尔值被改变了。 我对线程和android都很陌生,所以我想我只是错过了一些东西。
【问题讨论】:
标签: android multithreading infinite-loop touch-event ontouch