线程-while循环-[Android]
因此,在我进一步尝试在 android 中实现 while 循环时,我想出了下面的代码:
private boolean connected = false;
private Thread loop = new Thread() {
public void run() {
Looper.prepare();
while (connected) {
do_Something();
}
Looper.loop();
}
};
onCreate() {
//.....
ok = (Button) findViewById(R.id.button1);
ok.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (connected) {
try {
loop.start();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), "Exception caught", Toast.LENGTH_LONG).show();
}
}
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) {
//disconnects current connection
connected = false;
}
return true;
}
});
}
也就是说,我试图在触摸第一个按钮时将我的 UI 线程切换到将一遍又一遍地执行某些操作的线程直到触摸第二个按钮,在这种情况下,布尔变量 k 将关闭并完全停止按下第一个按钮时新创建的线程。我用谷歌搜索了“线程/处理程序/android while 循环”,但无济于事。对我想做的事情的任何帮助将不胜感激
简单地说,如何杀死通过按第二个按钮创建的线程?
So in my further attempts to implement a while loop in android I have come up with the code below :
private boolean connected = false;
private Thread loop = new Thread() {
public void run() {
Looper.prepare();
while (connected) {
do_Something();
}
Looper.loop();
}
};
onCreate() {
//.....
ok = (Button) findViewById(R.id.button1);
ok.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (connected) {
try {
loop.start();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), "Exception caught", Toast.LENGTH_LONG).show();
}
}
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) {
//disconnects current connection
connected = false;
}
return true;
}
});
}
That is, I am trying to on the touch of the first button have my UI thread switch to the thread that will do_something over and over again until the touch of the second button, in which case the boolean var k will switch off and completely stop the newly created thread from the button press of the first button. I have google'd "threads/handlers/android while loops" but to no avail. Any help towards what I am trying to do would be much appreciated
Simply put, how do I kill the thread that was created via pressing the second button?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您尝试过 AsyncTask 吗?您可以做什么...在第一个按钮单击时启动一个新的 AsyncTask 并在第二个按钮单击时取消它。
注意:这是伪代码...可能包含错误...只是想给您概述。希望这有帮助。
Did you tried AsyncTask ? What you can do...start a new AsyncTask on firstButton click and cancel it on secondButton click.
Note: This is pseudocode...might contain error...just want to give you overview. hope this help.