The program needs to switch on a hotspot with custom SSID and password, but I can't find any API to do so on Marshmallow.
Asked
Active
Viewed 978 times
1 Answers
0
You can use the following standalone class :
import android.content.*;
import android.net.wifi.*;
import java.lang.reflect.*;
public class ApManager {
//check whether wifi hotspot on or off
public static boolean isApOn(Context context) {
WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
try {
Method method = wifimanager.getClass().getDeclaredMethod("isWifiApEnabled");
method.setAccessible(true);
return (Boolean) method.invoke(wifimanager);
}
catch (Throwable ignored) {}
return false;
}
// toggle wifi hotspot on or off
public static boolean configApState(Context context) {
WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
WifiConfiguration wificonfiguration = null;
try {
// if WiFi is on, turn it off
if(isApOn(context)) {
wifimanager.setWifiEnabled(false);
}
Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
method.invoke(wifimanager, wificonfiguration, !isApOn(context));
return true;
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
Now once you have created the class the following permissions are to be added to your Manifest :
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
After doing the above, the following code toggles the Hotspot:
ApManager.configApState(MainActivity.this);
You need to pass the accurate context in place of MainActivity.this
.
I used this class a long ago and don't exactly remember the source I took it from.

Haresh Khanna
- 21
- 4
-
Still doesn't work. Nothing happens. The wifi just switches off, thats all. – NobleSiks Apr 08 '17 at 16:30
-
Which android version are you currently on? I am on Android 6.0.1, MIUI8. – Haresh Khanna Apr 09 '17 at 15:20