ntcho
ntcho

Reputation: 311

Wi-Fi Connection Listener

guys.

I have some problem with my wifi listener.

I have used BroadcastReceiver for this.

This is my code.

public class WiFiService extends BroadcastReceiver {

Context mcontext;

@Override
public void onReceive(Context mcontext, Intent intent) {
    NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

    if(info != null) {

        if(info.isConnected()) {
            WifiManager wifiManager = (WifiManager)mcontext.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();

            Log.d("WifiConnection", "Connected");
            this.mcontext = mcontext;

            Wifi();
        }
    }
}

private void Wifi() {
    WifiManager wifiManager = (WifiManager)mcontext.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    String bssid = wifiInfo.getBSSID();

    //Have something to do here.

    Log.d("WifiConnection", "HomeWifi");
}}

As you can see, there is a logger that says Connected and Wifi.

When my phone connectes to the wifi, th log shows like this.

11-02 16:45:22.611 6678-6678/com.bedrock.live D/WifiConnection: Connected
11-02 16:45:22.622 6678-6678/com.bedrock.live D/WifiConnection: HomeWifi
11-02 16:45:22.627 6678-6678/com.bedrock.live D/WifiConnection: Connected
11-02 16:45:22.627 6678-6678/com.bedrock.live D/WifiConnection: HomeWifi
11-02 16:45:25.842 6678-6678/com.bedrock.live D/WifiConnection: Connected
11-02 16:45:25.843 6678-6678/com.bedrock.live D/WifiConnection: HomeWifi

It repeats three times. Any ideas for showing this only one time?

Thanks.

Upvotes: 0

Views: 228

Answers (1)

Kingfisher Phuoc
Kingfisher Phuoc

Reputation: 8190

I don't think there is anything you can do to avoid it. The broadcast is sent by the system. However, I think you can hack it with a boolean flag as:

NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

if(info != null) {

    if(info.isConnected() && !flagIsConnected) {
        //state change from disconnected to connected
        flagIsConnected = true; // set flag here to 
        WifiManager wifiManager = (WifiManager)mcontext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();

        Log.d("WifiConnection", "Connected");
        this.mcontext = mcontext;

        Wifi();
    }else if(!info.isConnected() && flagIsConnected){
       //state change from connect to disconnected
       flagIsConnected = false;
    }
}

Upvotes: 1

Related Questions