简体   繁体   中英

Asynchronous socket communication in Android with threads

I managed to programm an app that communicates with a server. I can write and I can read. I even managed to do it with Java NIO.

My problem is that I have a endless while loop that is listening for new data to read. It blocks the whole program and I can't write anymore data.

I need a solution so the loop keeps running in background listening for new data to read while I send data.

Any suggestions?

Use AsyncTask . It was created just for this kind of jobs (doing long running background tasks, while still have a possibility to update UI).

You could either create a separate thread to handle the socket asynchronously and pass messages through a handler, or create a local service to handle the comms.

You should never do a long wait on the main (UI) thread.

If your loop is blocking the whole program there is something wrong with it. I don't see what other answer you can realistically expect until you post some code.

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