Android检查Wi-Fi Direct已激活

时间:2017-06-14 07:45:58

标签: android wifi-direct wifip2p

如何检查设备上是否已激活Wi-Fi Direct?

我试图通过以下方式检查Wi-Fi:

WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
return wifiManager.isWifiEnabled();

但是有些设备不支持同时使用Wi-Fi和Wi-Fi Direct(华为Honor 4C,它会在您激活Wi-Fi Direct时关闭Wi-Fi),因此这种方式不起作用。

WIFI_P2P_STATE_CHANGED_ACTION BroadcastReceiver中的div2听取there也是不可接受的,因为只有当我开始使用Wi-Fi Direct(如发现)时才会触发,但是我需要先检查一下它的状态。

2 个答案:

答案 0 :(得分:1)

你可以通过WifiDirectBroadcastReceiver这样做:

public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {

private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;

public WiFiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel) {
    super();
    this.mManager = manager;
    this.mChannel = channel;
}

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    Boolean isEnabled;

    if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
        // check if Wi-Fi is enabled 
        int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
        if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
            isEnabled = true;
        } else {
            isEnabled = false;
        }
    } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
        // get list of peers by WifiP2pManager.requestPeers()
    } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
        // Respond to new connections 
    } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
        // on device's wifi state changes
    }
}
}

答案 1 :(得分:0)

您应该能够使用ConnectivityManager来获取Wi-Fi的状态。

ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (mWifi.isConnected()) {
        // Do whatever
    }

请在清单ACCESS_NETWORK_STATE&& INTERNET。