Communicate worker thread with main thread

拜拜、爱过 提交于 2019-12-06 05:03:53

When you create the UDPServerThread, you could pass in a reference to the UDPSocketBackgroundService and then call a method on it (processPacket() for example) when packets are received. This processPacket() method will need to use some sort of synchronization.

Here's a small code excerpt of the related functions:

public class UDPSocketBackgroundService extends Service
{
    ....
    @Override
    public IBinder onBind(Intent arg0)
    {
        try
        {
            new Thread(myThreads, new UDPServerThread(this, "X", 8888)).start();
            // Notice we're passing in a ref to this  ^^^
        }
        ...
    }
    public void processPacket(DatagramPacket packet)
    {
        // Do what you need to do here, with proper synchronization
    }
}

public class UDPServerThread extends Thread
{
    private static final int MESSAGE_SIZE = 256;

    protected DatagramSocket socket = null;
    protected boolean end = false;
    protected UDPSocketBackgroundService = null;

    public UDPServerThread(UDPSocketBackgroundService service, String serverName, int port) throws IOException
    {
        super(serverName);
        this.service = service;
        socket = new DatagramSocket(port);
    }

    ...

    public void run()
    {
        while (!end)
        {
            try
            {
                byte[] buf = new byte[MESSAGE_SIZE];

                // Wait an incoming message.
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                socket.receive(packet);
                service.processPacket(packet);
            }
            ...
        }
        ...
    }
}

Notice that going this approach, the UDPSocketBackgroundService is now "tightly coupled" with the UDPServerThread. Once you get this working, you may consider refactoring it with a more elegant design where there is less coupling, but for now this should get you going :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!