Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
   }
like image 246
zaxy78 Avatar asked Dec 20 '11 06:12

zaxy78


2 Answers

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.

like image 150
Ciaran Fisher Avatar answered Oct 31 '22 12:10

Ciaran Fisher


No, all you could do is notify the user to turn on WiFi.

like image 36
Seshu Vinay Avatar answered Oct 31 '22 12:10

Seshu Vinay