puopg
puopg

Reputation: 573

How to update View from another thread

I have a UDPServer that is receiving packets right now and the code is below. Basically what happens when a packet is received is the toggle button should get swtiched on. It does, but the view only updates when i rotate the phone or press the menu button. I presume this is due to the view not being redrawn. I also feel like this has something to do with teh fact I am using a thread and theres an infinite loop and somehow the UI thread never sees the invalidate() to refresh the view. Should a UDPServer be using async tasks? Not sure if this is the best way to implement a UDPServer.

public class UDPServer extends Thread {
    public static final int SERVERPORT = 4444;
    private boolean isRunning = false;
    private String lastMessage = "";

    /**
     * Method to send the messages from server to client
     * 
     * @param message
     *            the message sent by the server
     */
    public void sendMessage(String message) {
    }

    @Override
    public void run() {
        super.run();
        isRunning = true;
        String message;
        byte[] lmessage = new byte[4096];
        DatagramSocket socket = null;
        DatagramPacket packet = new DatagramPacket(lmessage,
                lmessage.length);
        // Let the server continue to listen for incoming packets
        // Will listen on localhost and port 4444 for now
        while (isRunning) {
            try {
                InetAddress serverAddr = InetAddress
                        .getByName("192.168.1.107");
                socket = new DatagramSocket(SERVERPORT, serverAddr);
                socket.receive(packet);
                ToggleButton tglBtn = (ToggleButton) findViewById(R.id.toggleButton1);
                tglBtn.setChecked(true);
                // Get the data from the packet and react accordingly
                message = new String(lmessage, 0, packet.getLength());
                lastMessage = message;
                runOnUiThread(updateTextMessage);
                // processMessage(message);
                myView.invalidate();
            } catch (Throwable e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

Upvotes: 0

Views: 306

Answers (2)

stan0
stan0

Reputation: 11807

To invalidate a view from a non-ui thread you can use postInvalidate().

Upvotes: 0

Emmanuel
Emmanuel

Reputation: 13223

You should consider using AsyncTask; it was developed for exactly this. You perform the long running task in doInBackground(), which runs on a background Thread,and then update the UI in onPostExecute(), which runs on the UI Thread and gets the result returned from doInBackground().

Upvotes: 1

Related Questions