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

雨燕双飞 提交于 2019-11-28 07:39:18
Ciaran Fisher

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.

Seshu Vinay

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

On some devices, even though Wi-Fi direct is supported, it's not enabled due to some system bugs. Here's a more reliable way to check whether it's enabled (unfortunately it requires root) using Kotlin.

val matcher = "^mNetworkInfo .* (isA|a)vailable: (true|false)"
    .toPattern(Pattern.MULTILINE)
    .matcher(su("dumpsys ${Context.WIFI_P2P_SERVICE}"))
if (!matcher.find()) return "Root unavailable"
if (matcher.group(2) != "true") return "Wi-Fi Direct unavailable"
return "Wi-Fi Direct available"

This should work for Android 4.3 - 8.1. Check source code below:

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