Question

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.

Was it helpful?

Solution

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;
    }
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top