DarkVision
DarkVision

Reputation: 1423

BroadcastReceiver for wifi connection don't work correctly

I want to set my wifi off after a certain time when wifi is not connected. The probleme that occur to me is when i remove the wifi connection onreceive got call but say the network still connected. I don't understand why its connected didn't the state just change? Did the state change so much fast that it didn't have time to catch it?? Any help will be appreciate.

Here my receiver

class WifiDataReceiver extends BroadcastReceiver {
    public void onReceive(Context c, Intent intent) {
        Log.v("msg", "onReceive WifiDataReceiver");
        Log.v("msg", "mWifi : " + mWifi);
        cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
        mWifi = cm.getNetworkInfo(1).getState();
        if (mWifi != NetworkInfo.State.CONNECTED){
            try {
                Thread.sleep(disconnectionTimeout);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            wifiManager.setWifiEnabled(false);
            Log.v("msg", "Disconnect  WifiDataReceiver");

        } else {
            Log.v("msg", "connected");
        }
    }

Upvotes: 0

Views: 101

Answers (1)

pt2121
pt2121

Reputation: 11870

I have tested your code on 2 devices (GS3 and Samsung Charge). It worked fine. The state changed after I toggled wifi setup. My code is on github, here. And below is the log:

06-17 15:50:46.151: V/msg(12488): onReceive WifiDataReceiver
06-17 15:50:46.151: V/msg(12488): mWifi : DISCONNECTED
06-17 15:50:56.151: V/msg(12488): Disconnect  WifiDataReceiver
06-17 15:50:56.221: V/msg(12488): onReceive WifiDataReceiver
06-17 15:50:56.221: V/msg(12488): mWifi : DISCONNECTED
06-17 15:51:06.232: V/msg(12488): Disconnect  WifiDataReceiver
06-17 15:51:06.292: V/msg(12488): onReceive WifiDataReceiver
06-17 15:51:06.302: V/msg(12488): mWifi : DISCONNECTED
06-17 15:51:16.293: V/msg(12488): Disconnect  WifiDataReceiver
06-17 15:51:39.678: V/msg(12488): onReceive WifiDataReceiver
06-17 15:51:39.678: V/msg(12488): mWifi : CONNECTED
06-17 15:51:39.678: V/msg(12488): connected
06-17 15:51:39.708: V/msg(12488): onReceive WifiDataReceiver
06-17 15:51:39.708: V/msg(12488): mWifi : CONNECTED
06-17 15:51:39.708: V/msg(12488): connected
06-17 15:51:39.908: V/msg(12488): onReceive WifiDataReceiver
06-17 15:51:39.918: V/msg(12488): mWifi : CONNECTED
06-17 15:51:39.918: V/msg(12488): connected
06-17 15:51:39.918: V/msg(12488): onReceive WifiDataReceiver
06-17 15:51:39.918: V/msg(12488): mWifi : CONNECTED
06-17 15:51:39.918: V/msg(12488): connected

I think it might have something to do with your phone or ROM.

Upvotes: 1

Related Questions