本文介绍了沟通与主线程工作者线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个Android应用程序。

I'm developing an Android application.

这个应用程序将有一台服务器来启动一个DatagramSocket作为服务器。它会等待传入的消息。当socket得到一个消息,我会处理它。

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.

要启动一个UDP服务器套接字我将使用一个本地服务。这项服务将有一个工作线程我要去哪里听传入的消息。

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

这是我还的未完成辅助线程执行:

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

下面:

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.

正如你所看到的,我在Android开发的新手。

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

如果你知道一个更好的方法,请告诉我。

If you know a better approach, please tell me.

推荐答案

在创建UDPServerThread,你可以到UDPSocketBackgroundService一个引用传递,然后调用(比如)processPacket()上的方法时,接收的数据包。这processPacket()方法将需要使用某种形式的同步。

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.

下面是相关的功能的小code节选:

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

注意,去这种方法,UDPSocketBackgroundService现在是紧耦合的UDPServerThread。一旦你得到这个工作,你可以考虑用更优雅的设计,其中有较少的耦合重构它,但现在这应该让你去:)

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

这篇关于沟通与主线程工作者线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:46