0

I have been searching endless to find an answer to this. I want to create an Android app that switches on the Bluetooth when the WiFi disconnects. Im starting to think i cannot be done.

I thought it would be something like IF WiFi=Inactive THEN Bluetooth=On <- In theory However no where to be seen. i will be working in eclipse and compiling for the latest 4.4 if that helps.

Can anyone point me in the right direction. tell me what method im suppose to be using or how it can be done?

Anything else let me know.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
SStudios
  • 3
  • 5
  • I think you can set up a broadcast receiver to listen for changes in network connection. On the incoming intent you could check for network conditions and do your switch at that time. – James andresakis Nov 28 '13 at 00:00
  • Ahh thanks i see, im starting to see a picture now. i found some information for broadcast receiver i will post back later on today for update thanks a lot – SStudios Nov 28 '13 at 00:05

2 Answers2

1

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.

Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106
  • Hi yes thanks very much it did help. i added a Toast so it shows me when it receives the broadcast. it works perfectly. but now how do i turn on Bluetooth once it receives my broadcast. only part left. thanks in advanced – SStudios Dec 01 '13 at 22:38
  • Check this out: [How to enable/disable bluetooth programmatically in android](http://stackoverflow.com/questions/3806536/how-to-enable-disable-bluetooth-programmatically-in-android). – Simon Dorociak Dec 01 '13 at 22:58
  • That was the first thing i tried. It doesn't work. it says `Create variable` or `Create field` on "REQUEST_ENABLE_BT", also does it need to be on `OurReceiver.Java` or `MainAcitvity.Java` . thanks for your help – SStudios Dec 01 '13 at 23:04
  • Okay i started again from code you gave me. but the `if (ni.getDetailedState.equals(DetailedState.DISCONNECTING)` has an error syaing `getDetailedState cannot be resolved or is not a field` – SStudios Dec 01 '13 at 23:12
  • Check your imports, please. – Simon Dorociak Dec 01 '13 at 23:16
  • imports have been checked: `import android.content.BroadcastReceiver;` `import android.content.Context;` `import android.content.Intent;` `import android.net.NetworkInfo;` `import android.net.NetworkInfo.DetailedState;` `import android.net.wifi.WifiManager;` `import android.widget.Toast;` – SStudios Dec 01 '13 at 23:21
  • @SStudios `ni.getDetailedState()` it's function you cannot call it like variable. – Simon Dorociak Dec 02 '13 at 12:31
  • i am using the function as you are using it in the code above. – SStudios Dec 03 '13 at 15:24
  • @SStudios Sorry it was my typo mistake, source code in answer updated. – Simon Dorociak Dec 03 '13 at 15:27
  • thanks the app now compiles. however the app doest not do anything once WiFi is disconnected. if WiFi is on and i walk out of the house and it disconnects the Bluetooth remains off. thank you – SStudios Dec 03 '13 at 15:45
  • You need to simulate in with manual on/off wifi, but it works work me so your logic for enabling bluetooth is not correct. – Simon Dorociak Dec 03 '13 at 16:00
  • Thanks again that helped. it works perfectly now Bluetooth switches on when WiFi switches of. is there a way i could switch WiFi back on once Bluetooth disconnects – SStudios Dec 03 '13 at 16:27
  • @SStudios maybe yes, you need to find it out. currently i dont have a time to solve quetions.. – Simon Dorociak Dec 03 '13 at 16:41
0

It's pretty easy to determine when a network connection goes away. So you're half way there

The code:

public class NetworkStateReceiver extends BroadcastReceiver {

    private static Set<NetworkStateListener> listeners = new HashSet<NetworkStateListener>();

    public static void clearListeners() {
        listeners.clear();
    }
    public static void addListener(NetworkStateListener listener) {
        listeners.add(listener);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            NetworkInfo ni = (NetworkInfo) extras.get(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (ni != null) {
                for (NetworkStateListener listener : listeners) {
                    listener.stateChanged(ni);
                }
            }
        }
    }

    public interface NetworkStateListener {
        public void stateChanged(NetworkInfo networkInfo);
    }
}

In your manifest:

<receiver android:name="<your package>.NetworkStateReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        <action android:name="android.intent.action.PACKAGE_RESTARTED"/>
    </intent-filter>
</receiver>
Sky Kelsey
  • 19,192
  • 5
  • 36
  • 77