Android
Android

Reputation: 141

At the time of closing an application: How to stop a thread?

I use the following code to receive the data using UDP. When I click the back button my screen visual is closed and it shows the home screen. But a thread is working in the background (it receives the data from the UDP server). When I close the application I also need to stop the thread. How to stop a thread?

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();
}

Upvotes: 1

Views: 1311

Answers (1)

Dariusz Bacinski
Dariusz Bacinski

Reputation: 8660

You have to change while condition:

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()  
}

Upvotes: 3

Related Questions