Communicate worker thread with main thread

穿精又带淫゛_ 提交于 2020-01-02 09:53:50

问题


I'm developing an Android application.

This application will have a server to start a DatagramSocket as a server. It will wait for incoming message. When the socket get a message I will process it.

To start a UDP Server socket I'm going to use a Local Service. This service will have a worker thread where I'm going to listen to incoming messages.

This is my unfinished Local Service implementation:

public class UDPSocketBackgroundService extends Service
{
    private static final String TAG = "UDPSocketBackgroundService";
    private ThreadGroup myThreads = new ThreadGroup("UDPSocketServiceWorker");
    private Handler mServiceHandler;

    @Override
    public void onCreate()
    {
        super.onCreate();
        Log.v(TAG, "in onCreate()");
    }

    @Override
    public IBinder onBind(Intent arg0)
    {
        try
        {
            new Thread(myThreads, new UDPServerThread("X", 8888)).start();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

And this is my also unfinished Worker Thread implementation:

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

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

    public UDPServerThread(String serverName, int port) throws IOException
    {
        super(serverName);
        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);
                // TODO: Notify Service with packet received
            }
            catch (IOException e)
            {
                // TODO Mensaje de error.
                e.printStackTrace();
            }
        }
    }
}

Those classes have their own file (they are on different files).

Here:

socket.receive(packet);
//TODO: Notify Service with packet received

How can I notify service that we have received a packet? I want to send to service that packet also.

Here there is an example on how to communicate from Main thread to worker thread. But, I don't need that, I'm looking for an example on how to communicate from worker thread to service.

I've found this example, but I don't understand it very well because on that example both classes are declare it on the same file.

As you can see, I'm a newbie on Android development.

If you know a better approach, please tell me.


回答1:


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 :)



来源:https://stackoverflow.com/questions/10977729/communicate-worker-thread-with-main-thread

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