Wi-Fi连接侦听器

时间:2015-11-02 07:47:28

标签: android broadcastreceiver android-wifi wifimanager

我的wifi监听器有问题。

我已经使用了BroadcastReceiver

这是我的代码。

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");
}}

如您所见,有一个记录器显示ConnectedWifi

当我的手机连接到wifi时,日志显示如下。

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

重复三次。有没有想过只展示一次的想法?

感谢。

1 个答案:

答案 0 :(得分:1)

我认为你无法做任何事情来避免它。广播由系统发送。但是,我认为你可以使用布尔标志来破解它:

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;
    }
}