Recently, I am working on a small application. I need to set the AP (Access point) of the Android mobile phone through a program, which turns the mobile phone into a mobile hotspot and other machines can connect to the mobile phone through wifi ). I thought it was a very simple thing, but it took some twists and turns out to be done.
The options for configuring the AP are part of configuring wifi, so they are all in the WifiManager class. To obtain the WifiManager instance of the current system, follow these steps:
1 |
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
|
There are several key methods in this class to set the AP, but they are all hidden and cannot be called directly, so they can only be called through reflection.
The method to obtain the current AP status is:
1234 |
private Boolean getApState(WifiManager wifi) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Method method = wifi.getClass().getMethod("isWifiApEnabled"); return (Boolean) method.invoke(wifi); }
|
The WifiConfiguration class is used to configure the AP. The following is a set AP.
123456789101112 |
Private WifiConfiguration getApConfiguration () {WifiConfiguration apConfig = new WifiConfiguration (); // configure the hotspot name apConfig. SSID = "yourId"; apConfig. allowedAuthAlgorithms. set (WifiConfiguration. authAlgorithm. OPEN); apConfig. allowedKeyManagement. set (WifiConfiguration. keyMgmt. WPA_PSK); apConfig. allowedProtocols. set (WifiConfiguration. protocol. RSN); apConfig. allowedProtocols. set (WifiConfiguration. protocol. WPA); // configure the hotspot password apConfig. preSharedKey = "yourPassword"; return apConfig ;}
|
Apply AP configuration and enable AP to use another hidden MethodsetWifiApEnabled
.Note that you must disable the wifi of the current mobile phone before enabling the AP. Otherwise, the startup will fail.
123456789 |
private void setWifiAp() { Method method = wifi.getClass().getMethod( "setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE); wifi.setWifiEnabled(false); method.invoke(wifi, null, true); }
|
Finally, you must set several permissions in the AndroidManifest. xml file. Otherwisejava.lang.SecurityException: Permission Denied
. The permissions to be added are as follows:
1234 |
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /><uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /><uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
|
I have already placed the source code on github. If you need it, please checkout it on your own. Address: https://github.com/huangbowen521/APSwitch