【问题标题】:Wi-Fi Connection ListenerWi-Fi 连接监听器
【发布时间】:2015-11-02 07:47:27
【问题描述】:

伙计们。

我的 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

它重复了三遍。有什么想法可以只展示一次吗?

谢谢。

【问题讨论】:

    标签: android broadcastreceiver android-wifi wifimanager


    【解决方案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;
        }
    }
    

    【讨论】:

    • 所以我应该像Boolean flagIsConnected;一样使用它吗?
    • @BedrockDev 是的,你应该使用标志
    • Unable to start receiver com.bedrock.live.service.WiFiService: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 2022-08-11
    • 2023-04-04
    • 1970-01-01
    • 2020-02-20
    • 2017-02-21
    相关资源
    最近更新 更多