Domanda

I've recently written a small android application to send and receive UDP messages over a local network.
I have a UDP receiver thread that runs to listen for UDP packets, what I want to happen is a button to become enabled on the UI when a packet is received that contains a certain string of data. I know that this has to be done with a handler, the problem being that I have a small amount of knowledge about threads and very little knowledge about handlers.
would someone be able to shed some light on how a handler could be put into my code?
thanks

code:

public void startUDPlistener() {

    // Creates the listener thread
    LISTEN = true;
    Thread listenThread = new Thread(new Runnable() {

        @Override
        public void run() {

            try {

                Log.i(LOG, "Listener started!");
                DatagramSocket socket = new DatagramSocket(BROADCASTPORT);
                socket.setSoTimeout(1500);
                byte[] buffer = new byte[BUFFERSIZE];
                DatagramPacket packet = new DatagramPacket(buffer, BUFFERSIZE);


                while(LISTEN) {

                    try {

                        Log.i(LOG, "Listening for packets");
                        socket.receive(packet);
                        String data = new String(buffer, 0, packet.getLength());
                        Log.i(LOG, "UDP packet received from "+ packet.getAddress() +" packet contents: " + data);




                    }
                    catch(IOException e) {

                        Log.e(LOG, "IOException in Listener " + e);
                    }
                }

                Log.i(LOG, "Listener ending");
                socket.disconnect();
                socket.close();
                return;
            }

            catch(SocketException e) {

                Log.e(LOG, "SocketException in Listener " + e);

            }
        }
    });

    listenThread.start();

}
È stato utile?

Soluzione

You basically just add one and send either a Message or a Runnable.

private final Handler mUiThreadHandler = new Handler(Looper.getMainLooper());

void fromAnyThread() {
    final String importantDataFromBackGroundThread = "!!!";
    mUiThreadHandler.post(new Runnable() {
        @Override
        public void run() {
            System.out.println("Hi from Ui Thread:" + importantDataFromBackGroundThread);
        }
    });
}

The Handler handles all messages / runnables within the Thread it runs in. If you specify Looper.getMainLooper() you are guaranteed that this is the main thread.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top