WiFi Direct status

怎甘沉沦 提交于 2019-12-01 13:06:55

问题


Is it possible to specifically check that whether WiFi Direct is On or Off ? I wrote a code which can only update about the wifi status that whether it is connected or not,no matter it is Access point or WiFi Direct

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

                    if (mWifi.isConnected()) {

                    }
                    if (!mWifi.isConnected()) {


                    }

I want to specifically check about the WiFi Direct status.Please help.


回答1:


Yes, there is a way to do this. You use call this WIFI_P2P_STATE_CHANGED_ACTION to check if it is enabled or disabled. Some sample code is below:

First, you need a broadcast reciever:

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

Then, on the OnRecieve part of your code for the broadcast reciever, you have this code:

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


来源:https://stackoverflow.com/questions/20034736/wifi-direct-status

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!