I am writing an app that connects to a telnet server via wifi. I have a service that manages the socket connection. It all works fine, but when the phone sleeps it disconn
*set these permissions in your manifest
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
*Register a BroadcastReceiver for these actions filters in your manifest
<receiver android:name="com.myBroadcastReceiver" >
<intent-filter>
<action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
*Define your BroadcastReceiver´s implementation
public class myBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
NetworkInfo networkInfo = intent
.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo != null) {
Log.d(AppConstants.TAG, "Type : " + networkInfo.getType()
+ "State : " + networkInfo.getState());
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
//get the different network states
if (networkInfo.getState() == NetworkInfo.State.CONNECTING || networkInfo.getState() == NetworkInfo.State.CONNECTED) {
}
}
}
}
}
Not sure as to the exact way to do this but I think the ConnectivityManager would be a good place to start.
http://developer.android.com/reference/android/net/ConnectivityManager.html
you can get an instance of this class by calling Context.getSystemService(Context.CONNECTIVITY_SERVICE)
There are also some other good classes in android.net that you can use.
Hope that helps.
I know this is an old question but see the following developer documentation:
http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
Register a BroadcastReceiver
for ConnectivityManager.CONNECTIVITY_ACTION. In the onReceive
handler you can call NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO)
and then info.getType()
and check for ConnectivityManager.TYPE_WIFI
and do what you want then. :)