WiFi Direct状态

时间:2013-11-17 18:51:00

标签: android p2p android-wifi wifi-direct wifimanager

是否可以专门检查WiFi Direct是开还是关? 我写了一个代码,它只能更新无论是否连接的wifi状态,无论是接入点还是WiFi Direct

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

                    if (mWifi.isConnected()) {

                    }
                    if (!mWifi.isConnected()) {


                    }

我想专门查看WiFi Direct状态。请帮助。

1 个答案:

答案 0 :(得分:2)

是的,有办法做到这一点。您可以使用此WIFI_P2P_STATE_CHANGED_ACTION调用它来检查它是启用还是禁用。下面是一些示例代码:

首先,您需要一个广播接收器:

public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {

private WifiP2pManager mManager;
private Channel mChannel;
private MyWiFiActivity mActivity;

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

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

    if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
        // Check to see if Wi-Fi is enabled and notify appropriate activity
    } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
        // Call WifiP2pManager.requestPeers() to get a list of current peers
    } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
        // Respond to new connection or disconnections
    } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
        // Respond to this device's wifi state changing
    }
}
}

然后,在广播接收器代码的OnRecieve部分,您有以下代码:

@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Boolean isEnabled;
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
    int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
    if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
        isEnabled = true;
    } else {
        isEnabled = false;
    }
}
}