简体   繁体   中英

How can we create a handler in UI thread for sending data to another thread

I have 3 threads in android application. 1)UI thread 2)Server thread 3)Client thread

when a user enters a string and submits data from UI , I need to pass that data to server thread so that server will send it to clients , via bluetooth socket .

To send the data to server thread I am using the below code

 Toast.makeText(getApplicationContext(), "send data to server handler", Toast.LENGTH_SHORT).show();
        Handler serverHandler=new Handler(Looper.getMainLooper());
        Message msg=new Message();
        msg.obj=text.getText();
        serverHandler.sendMessage(msg);

In my understanding ,I need to create a handler from the looper related to server thread and send the message. Can somebody advise if this is the right way of creating handler objects from looper.

This is the server thread I am having

Looper.prepare();

                    serverHandler = new Handler() {
                        public void handleMessage(Message msg) {
                            // Act on the message
                            String data=(String)msg.obj;
                            try {
                                socket.getOutputStream().write(data.getBytes());
                            }
                            catch(Exception e){

                            }
                        }
                    };
                    Looper.loop(); 

To avoid any confusion, simply create an AsyncTask

  private class DataHandler extends AsyncTask<Void, Void, Void> {
        private String message = null;
        private Socket socket;

        public DataHandler(String message, Socket socket) {
            this.message = message;
            this.socket = socket;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                socket.getOutputStream().write(message.getBytes());
            } catch (Exception e) {

            }
            return null;
        }
    }

AsyncTask call

new DataHandler(text.getText(),socket).execute();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM