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!