-2

I'm new at socket programming and I've read several tutorials to have an idea on when to start. But I still have little knowledge about Android UI Thread and socket programming.

When using HTTP request, you should do the operation in a different thread to prevent the UI from blocking and getting an ANR. So my question is what about a socket connection? does it works the same as an HTTP request where the code execution stops until the device gets a response, therefore, I have to do the operations in a background thread to prevent ANR?

Christopher Francisco
  • 15,672
  • 28
  • 94
  • 206
  • 1
    Using HTTP request is basically the same as a socket connection. A HTTP request sets up a TCP connection, and then sends some text that is understandable by a program that knows the protocol HTTP. Thus, sending and receiving packets plus processing packet data will be blocking your app while working. The same works for a socket connection. Therefore you should always do your connections in a separate thread. EDIT: I cannot think of any application (android or not) that shouldn't use threads when handling network traffic, so one can consider it at least good practice to always use threads. – Pphoenix Jun 02 '14 at 12:29

2 Answers2

1

Yes, socket connection and read operations are blocking.

Asaf
  • 616
  • 2
  • 6
  • 17
0

For HTTP, you can use asynchronous HTTP libraries that work with Listeners in mind: http://loopj.com/android-async-http/

For Sockets, you can use AsyncTask to do things in background: Using AsyncTask for android network connection

You cannot do network connection on the main thread, it throws an Exception, because it freezes the application if it times out.

Community
  • 1
  • 1
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428