我已经编写了代码来为Android设备创建一个访问点。我已经在模拟器和真实设备上进行了测试。但它不起作用。我哪里弄错了?
public class MainWAP extends Activity {
WifiManager wifiManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_wap);
}
public void openWifi(View v) {
createWifiAccessPoint();
}
private void createWifiAccessPoint() {
if (wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
}
Method[] wmMethods = wifiManager.getClass().getDeclaredMethods();
boolean methodFound = false;
for (Method method: wmMethods) {
if (method.getName().equals("setWifiApEnabled")) {
methodFound = true;
WifiConfiguration netConfig = new WifiConfiguration();
netConfig.SSID = "AccessPoint";
netConfig.allowedAuthAlgorithms.set(
WifiConfiguration.AuthAlgorithm.OPEN);
try {
boolean apstatus = (Boolean) method.invoke(
wifiManager, netConfig, true);
for (Method isWifiApEnabledmethod: wmMethods) {
if (isWifiApEnabledmethod.getName().equals(
"isWifiApEnabled")) {
while (!(Boolean) isWifiApEnabledmethod.invoke(
wifiManager)) {};
for (Method method1: wmMethods) {
if (method1.getName().equals(
"getWifiApState")) {
int apstate;
apstate = (Integer) method1.invoke(
wifiManager);
}
}
}
}
if (apstatus) {
Log.d("Splash Activity",
"Access Point created");
} else {
Log.d("Splash Activity",
"Access Point creation failed");
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
if (!methodFound) {
Log.d("Splash Activity",
"cannot configure an access point");
}
}
}
答案 0 :(得分:7)
您的WiFiManager
绝对未初始化。
在onCreate
方法中添加以下内容:
wifiManager = (WiFiManager) getSystemService(Context.WIFI_SERVICE);
答案 1 :(得分:3)
您需要很少的东西才能使这段代码有效。
1)初始化wifiManager onCreate()
:
WifiManager wifiManager = (WiFiManager) getSystemService(Context.WIFI_SERVICE);
2)您需要在AndroidManifest.xml
:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_APN_SETTINGS" />
3)您的申请需要使用系统证书签名。
答案 2 :(得分:0)
使用反射来利用未记录的API的方法,在所有情况下都可能无法正常工作。 好吧,您可以尝试在清单文件中添加这些内容并尝试一下。
android.permission.ACCESS_WIFI_STATE
android.permission.CHANGE_WIFI_STATE
android.permission.WRITE_APN_SETTINGS