我有一个在 onStart() 方法中创建线程的 Activity 。 Thread 用于通过 TCP 读取网络数据,并在 while 循环中具有阻塞网络读取方法,该方法在每次递增时检查 bool 变量。
我的问题是,当使用返回键销毁 Activity 时,我将 bool 循环控制变量的值设置为 false,但线程不会完成,因为它卡在阻塞网络方法上。
public class MyActivity extends Activity implements Runnable
{
Thread thread;
boolean loopControl;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
protected void onStart()
{
super.onStart();
loopControl=true;
thread = new Thread(this);
thread.start();
}
public void run()
{
while(loopControl)
{
directories = (Vector<String>) TCPFunctions.inputStream.readObject();
}
}
protected void onDestroy()
{
super.onDestroy();
loopcontrol = false;
}
}
我该如何完成我想要的线程,因为它会在再次启动此 Activity 时产生问题。
实际上每次 Activity 启动时它都有一些数据要从服务器读取
最佳答案
在你的 onDestroy() 方法中尝试
thread.interrupt();
thread=null;
关于Android 在 Activity 被销毁时停止 Activity 中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11811981/