How to do If “WiFi disconnects then Bluetooth turns on” function?
So here is solution that came to my head:
At first you need to create mechanism that will listen for Wi-Fi network connection changes. Yes, i'm talking about BrodcastReceiver with proper intent-filters. So at first we need to define our receiver that will listen for network changes.
I mentioned intent-filters. At a glance intent-filters ->
you can imagine them like "events" where each receiver can register one or events and when event is fired up and receiver is able to listen it (has assigned that event) will be immediately invoked.
Especially in you case you need this event (usually called action) that listens for Wi-Fi connectivity changes:
<action android:name="android.net.wifi.STATE_CHANGE" />
Same action you can retrieve through source-code:
WifiManager.NETWORK_STATE_CHANGED_ACTION
Then you have almost all things you need. But now you need to retrieve in our receiver actual state of Wi-Fi connectivity.
Answer is to use NetworkInfo class that wraps information about network. And this Object you are able to obtain from action above (see final source code at the end of answer).
And here it's pretty simple, when state of Wi-Fi will be disconnected you just enable Bluetooth.
Here is final source code:
public class NetworkReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// action when network connectivity changed
if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
// gets network info from intent action
NetworkInfo ni = intent.getParcelableExtra(
WifiManager.EXTRA_NETWORK_INFO);
// if network state is disconnecting or disconnected
if (ni.getDetailedState().equals(DetailedState.DISCONNECTING)
|| ni.getDetailedState().equals(DetailedState.DISCONNECTED)) {
// turns Bluetooth on
}
}
}
}
Notes:
1. I've done a few tests and now i know that in Android you are able to detect only these states of network with getState() and getDetailedState():
CONNECTED
CONNECTING
DISCONNECTED
OBTAINING_IPADDR
and CAPTIVE_PORTAL_CHECK
All other states not working or works only some devices which is not very good but we can't do nothing (except Google Team).
2. Don't forget to add proper permissions to your manifest.xml to be able to read current state of network etc.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
3. I recommend you to look at BroadcastReceivers, Intents and Intent Filters and things related to Wi-Fi.
Hope it helps you.