我已经编写了代码来为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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
你WiFiManager肯定没有初始化.
在你的onCreate方法中添加:
wifiManager = (WiFiManager) getSystemService(Context.WIFI_SERVICE);
Run Code Online (Sandbox Code Playgroud)
使用反射来利用未记录的 API 的方法可能无法在所有情况下都能正常工作。好吧,您可以尝试将这些添加到您的清单文件中并尝试一下。
android.permission.ACCESS_WIFI_STATE
android.permission.CHANGE_WIFI_STATE
android.permission.WRITE_APN_SETTINGS
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10728 次 |
| 最近记录: |