Programming sockets for Android without a WIFi connection

I wrote an application to start my server at home remotely. The application works without problems in the emulator, as well as on my smartphone (HTC desire, Android 2.2) when WiFi is on. However, this does not work when WiFi is off.

Before rebooting, first check if it is running. For this, I use sockets, and I first connect to the dyndns address. After that, I try to connect to my ip-box, where I can turn on my computer by sending commands through the socket.

When the connection to this socket fails, I know that the server is not running.

Relevant Code:

socket = new Socket(); socket.connect(new InetSocketAddress(serverName, port), 10000); status = socket.isConnected() == true; socket.close(); 

If an exception (SocketException) exists, I know that the server is not running. This approach works fine when I turned on WiFi. However, if Wi-Fi is not turned on, the connection always talks about it, even if it cannot establish a connection because the server is unavailable.

Is there a way to check if the connection is established even if WiFi is disconnected?

Any suggestions are welcome!

Thanks,

Rudy

+7
source share
2 answers

Try opening your socket as follows:

 public boolean connect(String ip, int port) { try { this.clientSocket = new Socket(ip, port); clientSocket.setSoTimeout(timeout); this.outToServer = new DataOutputStream(clientSocket .getOutputStream()); this.inFromServer = clientSocket.getInputStream(); isconnected = true; } catch (IOException e) { Log.e("TCPclient", "connection failed on " + ip + ":" + port); isconnected = false; return isconnected; } Log.e("TCPclient", "connection to " + ip + " sucessfull"); return isconnected; } 

If the connection fails, it throws an IOException (work when Wi-Fi is turned on and there is no server, and when Wi-Fi is not turned on (desire of HTC 2.3)).
This code is not entirely correct, it is just a short version

EDIT Try checking wfi state like this (this is not practical, but it should work)

  public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (ni.isConnected()) { Toast.makeText(this,"Wifi enabled", Toast.LENGTH_LONG).show(); Log.d("WiFiStateTestActivity", "WiFi!"); } else { Toast.makeText(this,"Wifi not enabled", Toast.LENGTH_LONG).show(); Log.d("WiFiStateTestActivity", "not WiFi!"); } } 
+2
source

Remember to set the permission in manifest.xml to allow your application to open the socket.

+1
source

All Articles