I am required to design an application in Android which requires the phone to connect to a server by opening a socket. I am able to achieve this when I am just connected to the particular wifi network (ie the Wifi network which hosts the server ) but in a situation when I am connected to the wifi network and the Mobile data network I get a socket exception thrown as android tries to connect the socket over the mobile network
I have already been able to connect the device when its just connected to the wifi of the device that needs the socket connection to be established
static class StartTCPconnection extends AsyncTask<Void, Void, Void> {
final WeakReference<RemoteActivity> activity;
StartTCPconnection(WeakReference<RemoteActivity> activity) {
this.activity = activity;
}
@Override
protected Void doInBackground(Void... voids) {
try {
socket = new Socket("192.168.4.1", 900);
Log.d(TAG, "is socket connected ? ...." + socket.isConnected());
printWriter = new PrintWriter(socket.getOutputStream(), true);
Log.i(TAG, "Checking if socket is really connected " + (socket.getLocalSocketAddress()));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (socket != null) {
if (socket.isConnected() && isWifi) {
Log.d(TAG, "onPostExecute: " + socket.isConnected());
Toast.makeText(activity.get(), "Connection established", Toast.LENGTH_SHORT).show();
Log.e(TAG, "onPostExecute: " + activity.get().getSharedPreferences(Constants.REMOTE_SWITCH_SHARED_PREFERENCE, Context.MODE_PRIVATE).getInt(Constants.REMOTE_SWITCH_KEY, 99));
if (activity.get().getSharedPreferences(Constants.REMOTE_SWITCH_SHARED_PREFERENCE, Context.MODE_PRIVATE).getInt(Constants.REMOTE_SWITCH_KEY, 1) == 1) {
activity.get().joyStickFragment.checkSocketInstance(socket);
activity.get().joyStickFragment.changeUIForConnect();
} else if (activity.get().getSharedPreferences(Constants.REMOTE_SWITCH_SHARED_PREFERENCE, Context.MODE_PRIVATE).getInt(Constants.REMOTE_SWITCH_KEY, 1) == 2) {
Log.e(TAG, "onPostExecute:Check " + socket.isConnected());
activity.get().buttonRemoteFragment.checkSocketInstance(socket);
activity.get().buttonRemoteFragment.changeUIForConnect();
}
activity.get().connectionIndicatorImage.setImageResource(R.drawable.avishkaar_logo_on);
activity.get().wifiIndicator.setImageResource(R.drawable.wifi_connected_icon);
}
} else {
// Toast.makeText(activity.get(), "Wrong Wifi Network connected", Toast.LENGTH_SHORT).show();
}
}
}
The above mentioned code connects me to the socket if the only network available is the WiFi of the device and the mobile network is turned off