Android sends data from the main UI thread to another thread

I need to send some data from the main stream to another stream. I already read a lot of material about threads, syntheses, and handlers, but maybe they created some confusion for me. I read that I need to create a Handler for my "second thread" so that I can send messages from the main thread (now I don’t worry about sending anything to the main thread).

I need a second thread to connect to the server (via a socket) and send some date to some user events. I am trying to do this efficiently (do not open or close unnecessary socket connections). So I wonder where should I put my open socket command? In addition, in the handler handleMessage () method, I need a link to the socket output stream to send data to the server.

I have the following code:

protected void initThread(){
    this.thread = new HandlerThread(WorkerHandler.class.getCanonicalName()){        

        @Override
        public void run() {
            super.run();
            try{
                handler = new WorkerHandler(getLooper());
            }catch(Exception e){
                e.printStackTrace();
            }               
        }

    };
    this.thread.start();
}

The initThread () method is called in the onCreate () method of my activity.

Here's the code for my handler class:

public class WorkerHandler extends Handler {

protected Socket socket;
protected BufferedWriter writer;

public WorkerHandler(Looper looper) throws Exception{
    super(looper);      
    this.socket = new Socket("192.168.1.7", 5069);
    this.writer = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream(), "utf-8"));

}

public BufferedWriter getWriter(){
    return this.writer;
}

public Socket getSocket(){
    return this.socket;
}

@Override
public void handleMessage(Message msg) {
    Draw draw = (Draw) msg.obj;
    if (draw != null){          
        if (getWriter() != null){
            try{
                getWriter().write(DrawUtil.toJson(draw)+"\n");
                getWriter().flush();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}

}

And again in my activity, I run the sendDataToServer () method

protected void sendDataToServer(){
    Draw draw = new Draw(getFlowType(), getID(), getSeq(), Calendar.getInstance(), startX, startY, endX, endY);
    if (getWorkerHandler() != null){
        Message msg = getWorkerHandler().obtainMessage();
        msg.obj = draw;
        getWorkerHandler().sendMessage(msg);
    }       
}

But my reference to the WorkerHandler object is always null. I am pretty sure that I misunderstood some concepts ... Could you give me some advice?

Thanks a lot!

+4
3

. , HandlerThread. A HandlerThread Thread, a Looper. run() HandlerThread. . , run() HandlerThread Looper.

initThread() :

    @Override
    public void run() {
        super.run(); // <-- This call runs the Looper loop and doesn't complete!!
        try{
            handler = new WorkerHandler(getLooper());
        }catch(Exception e){
            e.printStackTrace();
        }               
    }

, run() super.run(). . , initThread() .

HandlerThread(), run(). , - , ( Runnable s) . :

    HandlerThread handlerThread = new HandlerThread("myHandlerThread");
    handlerThread.start();
    // Now get the Looper from the HandlerThread so that we can create a Handler that is attached to
    // the HandlerThread
    // NOTE: This call will block until the HandlerThread gets control and initializes its Looper
    Looper looper = handlerThread.getLooper();
    // Create a handler attached to the background message processing thread
    handler = new Handler(looper, this);

Runnable "". handleMessage() create.

EDIT:

WorkerHandler , ( Worker, Handler, Handler.Callback ):

public class Worker implements Handler.Callback {

    protected Socket socket;
    protected BufferedWriter writer;

    public Worker() throws Exception{    
        this.socket = new Socket("192.168.1.7", 5069);
        this.writer = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream(), "utf-8"));
    }

    public BufferedWriter getWriter(){
        return this.writer;
    }

    public Socket getSocket(){
        return this.socket;
    }

    @Override
    public void handleMessage(Message msg) {
        Draw draw = (Draw) msg.obj;
        if (draw != null){          
            if (getWriter() != null){
                try{
                    getWriter().write(DrawUtil.toJson(draw)+"\n");
                    getWriter().flush();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}

Worker Handler. :

    HandlerThread handlerThread = new HandlerThread("myHandlerThread");
    handlerThread.start();
    Looper looper = handlerThread.getLooper();
    // Create an instance of the class that will handle the messages that are posted
    //  to the Handler
    Worker worker = new Worker();
    // Create a Handler and give it the worker instance to handle the messages
    handler = new Handler(looper, worker);
+3

, Java /, .. BlockingQueue, , .

public class SendingWorker {
    private final BlockingQueue<Draw> sendQueue = new LinkedBlockingQueue<Draw>();
    private volatile Socket socket;

    public void start() {
        thread.start();
    }

    public void stop() {
        // interrupt so waiting in queue is interrupted
        thread.interrupt();
        // also close socket if created since that can block indefinitely
        Socket socket = this.socket;
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // adding to queues is thread safe
    public void send(Draw draw) {
        sendQueue.add(draw);
    }

    private final Runnable task = new Runnable() {
        @Override
        public void run() {
            try {
                socket = new Socket(InetAddress.getLocalHost(), 8000);
                OutputStream out = socket.getOutputStream();
                while (true) {
                    Draw draw = sendQueue.take();
                    out.write(draw);
                    out.flush();
                }
            } catch (Exception e) {
                // handle 
            } finally {
                // cleanup
            }
        }
    };
    private final Thread thread = new Thread(task);
}
+1

...... : IntentFilter ,

Intent intentFilter=new IntentFilter();
intentFilter.addAction("YOUR_INTENT_FILTER");

BroadcastReceiver ,

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    /** Receives the broadcast that has been fired */
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction()=="YOUR_INTENT_FILTER"){
           //HERE YOU WILL GET VALUES FROM BROADCAST THROUGH INTENT EDIT YOUR TEXTVIEW///////////
           String receivedValue=intent.getStringExtra("KEY");
        }
    }
};

onResume() ,

registerReceiver(broadcastReceiver, intentFilter);

And finally, Unregister BroadcastReceiver in onDestroy () like,

unregisterReceiver(broadcastReceiver);

Now the most important part ... You need to start broadcasting from the background thread to send the values ​​..... like so,

Intent i=new Intent();
i.setAction("YOUR_INTENT_FILTER");
i.putExtra("KEY", "YOUR_VALUE");
sendBroadcast(i);

.... greetings :)

+1
source

All Articles