我可以通过代码打开 WiFi-Direct 吗?在 Android API-14 (ICS) 上 [英] Can I turn on WiFi-Direct from code? on Android API-14 (ICS)
问题描述
我在 Android 4.0 上使用来自谷歌的新 Wi-Fi Direct API并在示例代码中,他们将用户发送到设置,以激活 WiFi -直接模式.
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???
他们提供的只是侦听 WIFI_P2P_STATE_CHANGED_ACTION 意图,然后使用此代码
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
}
推荐答案
是的,有一种使用反射的方法.适用于我的 GSII(在非 Wifi Direct HTC Sensation 上正常失败)但由于这是反射,它可能不适用于所有手机.
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();
}
请注意:
在 Jelly Bean 及更高版本上,当您尝试使用 WifiP2pManager
API 时,WiFi-Direct 会自动启用(只要 WiFi 处于开启状态),因此无需使用此 hack.
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.
这篇关于我可以通过代码打开 WiFi-Direct 吗?在 Android API-14 (ICS) 上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!