Example: Android bi-directional network socket using AsyncTask

后端 未结 3 2071
醉酒成梦
醉酒成梦 2020-11-27 11:48

Most of the network socket examples I found for Android were one directional only. I needed a solution for a bi-directional data stream. I eventually learned of the AsyncTas

3条回答
  •  一向
    一向 (楼主)
    2020-11-27 12:12

    Your SendDataToNetwork does not run on the same thread as doInBackground(). There is a possibility that SendDataToNetwork would start sending data before socket is ready.

    To avoid all this just use SendDataToNetwork to save data and signal to background thread that data is ready to be sent.

    Since there is possibility that user can press button multiple times, while the old data is still being sent, you should have synchronized Queue inside NetworkTask. Then:

    1. Background thread sets up the socket connection and then goes to sleep (via wait()).
    2. On button press, SendDataToNetwork adds data to queue and wakes up the background thread (via notify()).
    3. When background thread wakes up, it first checks the finish flag. If set, it closes connections and exits. If not it reads data from Queue, sends it to network and goes back to sleep.
    4. You should have finish() method which sets a finish flag (atomic variable, like boolean) and wakes the background thread. This is a way to gracefully exit the background thread.

    Take a look at how thread synchronization is done: http://www.jchq.net/tutorial/07_03Tut.htm

提交回复
热议问题