在关闭应用程序时:如何停止线程?

时间:2010-07-05 05:00:27

标签: android

我使用以下代码使用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();
}

1 个答案:

答案 0 :(得分:3)

您必须更改while条件:

class Server implements Runnable {
    private boolean running;

    public void run() {
        running = true;

        while (running) {
            // do stuff here
        }
    }
    public stop() {
        running = false
    }
}

protected void onStop() {
     fst.stop()  
}