简体   繁体   中英

Android/Sockets - How to send information from main UI thread to socket thread?

I've been reading through forums for the past day and I can't seem to find an answer that would help solve my problem.

I am trying to create an android socket/game client which:

  1. Connects to the server on a new socket on a separate thread from the UI (which I want to keep open)
  2. Listens on the socket for messages from the server and sends it to the UI thread using a handler.
  3. Obtains information from the main UI thread (ie user inputs, gets textview, buttonclicks) and then emits the information to the server.
  4. Continues listening/sending for the rest of the activity.

I am having a lot of difficulty with implementing #3. The socket that is initially connected to the server is in its own thread, which I want to keep open indefinitely. What is the best way to get information from the main UI thread so that I can use that thread and socket to send information to the server?

I see a lot of posts about returning information from a background thread to the UI thread but not the other way around. Is there a standard way of doing this?

Thanks!

I've found a solution for this where I used a BlockingQueue that is shared between the UI thread and the socket thread. The UI thread uses queue.put() when it wants to place information that is to be emitted to the server, and the socket thread waits on queue.take() to get the information and send it to the server.

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