1
我使用下面的代碼來使用UDP接收數據。當我點擊後退按鈕時,我的屏幕視覺被關閉,並顯示主屏幕。但是一個線程正在後臺工作(它從UDP服務器接收數據)。當我關閉應用程序時,我也需要停止線程。如何停止線程?在關閉應用程序時:如何停止線程?
public void onClick(View view) {
port=Integer.parseInt(etd_port.getText().toString());
etd_port.setCursorVisible(false);
Thread fst = new Thread(new Server());
fst.start();
}
public class Server implements Runnable {
private String tagid="",roomid="";
public final int SERVERPORT = port;
private DatagramSocket ds;
private String recdata;
@Override
public void run() {
int buffer_size = 1024;
byte buffer[] = new byte[buffer_size];
try {
ds = new DatagramSocket(SERVERPORT);
while (true) {
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
ds.receive(p);
Log.d("MY UDP ","After Receive");
recdata=new String(p.getData(),0,p.getLength());
Log.d("Receive data ",recdata);
}
} catch(Exception e){
Log.e("MY UDP ", " Error", e);
}
}
}
......
@Override
protected void onStop() {
finish();
fst.stop();
super.onStop();
}