Enable Access Point in android programatically

bozhi91

New member
Sep 17, 2019
1
0
0
I'm trying to enable the wifi Access-Point on android device programmatically. The access-pint is already created and works fine. I only want to enable/disable it by code. The code doesn't work very well. The AP is enabled(by code) but I can't connect to the AP from any other device. However, if I disable and then enable the AP manually, then I can connect to the AP. Here's my code:

Code:
final class WifiApManager {
    private static final int WIFI_AP_STATE_FAILED = 4;
    private final WifiManager mWifiManager;
    private final String TAG = "Wifi Access Manager";
    private Method wifiControlMethod;
    private Method wifiApConfigurationMethod;
    private Method wifiApState;

    @SuppressLint("RestrictedApi")
    public WifiApManager( Context context) throws SecurityException, NoSuchMethodException {
        context           = Preconditions.checkNotNull(context);
        mWifiManager      = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        wifiControlMethod = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class,boolean.class);
        wifiApConfigurationMethod = mWifiManager.getClass().getMethod("getWifiApConfiguration",null);
        wifiApState = mWifiManager.getClass().getMethod("getWifiApState");
    }
    @SuppressLint("RestrictedApi")
    public boolean setWifiApState( WifiConfiguration config, boolean enabled) {
        config = Preconditions.checkNotNull(config);
        try {
            if (enabled) {
                mWifiManager.setWifiEnabled(!enabled);
            }
            return (Boolean) wifiControlMethod.invoke(mWifiManager, config, enabled);
        } catch (Exception e) {
            Log.e(TAG, "", e);
            return false;
        }
    }
    public WifiConfiguration getWifiApConfiguration() {
        try{
            return (WifiConfiguration)wifiApConfigurationMethod.invoke(mWifiManager, null);
        }
        catch(Exception e)
        {
            return null;
        }
    }
    public int getWifiApState() {
        try {
            return (Integer)wifiApState.invoke(mWifiManager);
        } catch (Exception e) {
            Log.e(TAG, "", e);
            return WIFI_AP_STATE_FAILED;
        }
    }
}

All the permissions are granted in the manifest file and I don't see any error logs in the console. Can you tell me if I'm missing something?

Thanks!
 

Trending Posts

Members online

Forum statistics

Threads
956,229
Messages
6,967,014
Members
3,163,488
Latest member
CHirsRoot