Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create Socket connection in Android?

I have an application in which I need to create a socket connection. My requirement is: once my socket connection is established it needs to be alive until I personally close it. And every 3 minutes I have to send data packets to the other end. Can anyone provide me some code samples that will help me to do this?

like image 892
Nilanchala Panigrahy Avatar asked Sep 12 '11 07:09

Nilanchala Panigrahy


People also ask

What is socket connection Android?

A socket is an endpoint for communication between two machines. The actual work of the socket is performed by an instance of the SocketImpl class. An application, by changing the socket factory that creates the socket implementation, can configure itself to create sockets appropriate to the local firewall.

What is a socket connection?

A socket is a communications connection point (endpoint) that you can name and address in a network. Socket programming shows how to use socket APIs to establish communication links between remote and local processes.

How do you know if a socket is connected?

If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; otherwise, the socket is no longer connected.

What is the use of Socket.IO in Android?

Listening on events​ Like I mentioned earlier, Socket.IO is bidirectional, which means we can send events to the server, but also at any time during the communication the server can send events to us. We then can make the socket listen an event on onCreate lifecycle callback.


1 Answers

Socket connections in Android are the same as in Java: http://www.oracle.com/technetwork/java/socket-140484.html

Things you need to be aware of:

  1. If phone goes to sleep your app will no longer execute, so socket will eventually timeout. You can prevent this with wake lock. This will eat devices battery tremendously - I know I wouldn't use that app.
  2. If you do this constantly, even when your app is not active, then you need to use Service.
  3. Activities and Services can be killed off by OS at any time, especially if they are part of an inactive app.

Take a look at AlarmManager, if you need scheduled execution of your code.

Do you need to run your code and receive data even if user does not use the app any more (i.e. app is inactive)?

like image 188
Peter Knego Avatar answered Sep 17 '22 09:09

Peter Knego