Can I turn on WiFi-Direct from code? on Android API-14 (ICS)

zaxy78 picture zaxy78 · Dec 20, 2011 · Viewed 10.2k times · Source

I'm using the new Wi-Fi Direct API from google on Android 4.0 and in Sample code they send the User to Settings, to activate WiFi -Direct Mode.

Is there a way to Start it by code???

all they offer is to listen to WIFI_P2P_STATE_CHANGED_ACTION intent, and then use this code

String action = intent.getAction();

if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {

   // UI update to indicate wifi p2p status.
   int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);

   if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
       // Wifi Direct mode is enabled

   } else {
       // Wifi Direct mode is disabled
   }

Answer

Ciaran Fisher picture Ciaran Fisher · Oct 31, 2012

Yes there is a way using reflection. Works on my GSII (and fails gracefully on non Wifi Direct HTC Sensation) but as this is reflection it may not work on all phones.

p2pManager = (WifiP2pManager) getSystemService(WIFI_P2P_SERVICE);
channel = p2pManager.initialize(getApplicationContext(),
        getMainLooper(), null);

try {
    Class<?> wifiManager = Class
            .forName("android.net.wifi.p2p.WifiP2pManager");

    Method method = wifiManager
            .getMethod(
                "enableP2p",
                new Class[] { android.net.wifi.p2p.WifiP2pManager.Channel.class });

    method.invoke(p2pManager, channel);

} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Please note:

On Jelly Bean and above, when you try to use the WifiP2pManager API, WiFi-Direct is automatically enabled (as long as WiFi is on), so there is no need to use this hack.