0

I am building an Android application that controls a device on the same network (details are irrelevant). The connection is set through TCP with sockets.

Here's what I'm trying to do :

  • Show a dialog when the app launches asking the user to connect (the dialog has already been built!)
  • Interrupt the activity if the connection is lost, and show another dialog

The app is built with a MainActivity, and a Fragment layout to manage the different tabs. Keep in mind that I am fairly new to Android programming, and I am mostly looking for the best way to code this instead of tinkering around :)

For now, relatively to the connection, I have a MainActivity that instantiate a "Connection" object in its onCreate() method. "Connection" itself executes an Asynctask when invoked to create and bind the socket to the server.

Thank you for your help!

Fluffy
  • 857
  • 1
  • 9
  • 20

2 Answers2

0

you can check this answered question :

How to check if TCP socket is connected in android app

and you can make it check every {1-5} sec using asyncTask and if its not connected , it throws a new dialog

Community
  • 1
  • 1
0

you can use to following code for checking to internet connection :

 ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
            connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
   //write the code which established connection with server
}else{
   // generate a alert
}
Bhunnu Baba
  • 1,742
  • 15
  • 22
  • Thank you for your input! Isn't this just checking if the device is connected to the Internet? – Fluffy May 02 '16 at 09:52
  • ya of course it only check to connectivity of device with internet. – Bhunnu Baba May 02 '16 at 09:59
  • The device itself doesn't need to be connected to the internet. I connect to a server on the same network, it has no internet connection whatsoever. I just need to check periodically if the socket is still properly bound to the server – Fluffy May 02 '16 at 11:34
  • then you can follow below link: http://stackoverflow.com/questions/698964/checking-if-a-clientsocket-has-disconnected-in-java-hangs – Bhunnu Baba May 03 '16 at 07:21