将线程共享给另一个类

时间:2013-06-18 08:17:11

标签: java android multithreading design-patterns

我在为Android设计多线程应用程序时遇到问题。

我有app有两个活动(MainActivity,LightActivity)。我需要他们两个与服务器通信。我想我需要另一个独立的线程(IncomingThread)来处理从服务器到我的活动的通信,但是不知道让它可用于所有两个活动。

现在我已经完成了这个部分解决方案:

public class MainActivity extends Activity {


private DatagramSocket clientSocket = null;
private final byte[] ipNeuron = {(byte)192,(byte)168,(byte)1,(byte)129};
private final int port = 9876;
private boolean ListenerWorks = true;
byte[] bData = new byte[1024];
Thread IncomingThread;
DatagramSocket serverSocket;

final Handler myHandler =  new Handler(){
    @Override
    public void handleMessage(Message msg) {

        updateUI(msg.obj.toString());
    }

};



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); 

    ListenerWorks=true;


    IncomingThread =  new Thread(new Runnable() {

        @Override
        public void run() {

            byte[] receiveData ;
            String sentence;
            DatagramPacket receivePacket;
            Message msg;
            serverSocket = null;
            try {
                Thread.sleep(2000); 
                serverSocket = new DatagramSocket(port);
                serverSocket.setSoTimeout(250);
                while (ListenerWorks) {

                    msg = myHandler.obtainMessage();
                    receiveData = new byte[1024];
                    receivePacket = new DatagramPacket(receiveData, receiveData.length);
                    serverSocket.receive(receivePacket);
                    sentence = new String(receivePacket.getData()).trim();
                    if (sentence.length()!=0){
                        msg.obj=sentence;
                        myHandler.sendMessage(msg);
                    }
                }
            } 
            catch (Exception e) {
                e.printStackTrace();
            }
            serverSocket.close();
        }

    });
       IncomingThread.start();

}


private void updateUI(String msg){
    //handle msg and update UI      
}

}

public class LightActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_light);

    /*
    how to set up handler to obtain messages from IncommingThread?
    how to set up some pointer to IncommingThread?

    */          

}

private void updateUI(String msg){
//Update my UI 
}

}

是否可以从其他活动(LightActivity)访问IncommingThread? 我知道其中一个解决方案可以设置服务来处理通信,但我认为它的工作方式很多。

0 个答案:

没有答案