Android 热点开关状态的判断和获取热点ssid

最近在做Android盒子开发的时候,需要对热点进行开关和对状态的判断,经过查询相关资料找到解决方案
WifiManager.java源码,getWifiApState() 获取开关的状态

/**
     * Gets the Wi-Fi enabled state.
     * @return One of {@link #WIFI_AP_STATE_DISABLED},
     *         {@link #WIFI_AP_STATE_DISABLING}, {@link #WIFI_AP_STATE_ENABLED},
     *         {@link #WIFI_AP_STATE_ENABLING}, {@link #WIFI_AP_STATE_FAILED}
     * @see #isWifiApEnabled()
     *
     * @hide Dont open yet
     */
    public int getWifiApState() {
        try {
            return mService.getWifiApEnabledState();
        } catch (RemoteException e) {
            return WIFI_AP_STATE_FAILED;
        }
    }

如果getWifiApState()被隐藏,就得调用反射来获取

 public static boolean isWifiApOpen(Context context) {
        try {
            WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            //通过放射获取 getWifiApState()方法
            Method method = manager.getClass().getDeclaredMethod("getWifiApState");
            //调用getWifiApState() ,获取返回值
            int state = (int) method.invoke(manager);
            //通过放射获取 WIFI_AP的开启状态属性
            Field field = manager.getClass().getDeclaredField("WIFI_AP_STATE_ENABLED");
            //获取属性值
            int value = (int) field.get(manager);
            //判断是否开启
            if (state == value) {
                return true;
            } else {
                return false;
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return false;
    }

通过 getWifiApState() 方法返回值的注释,可以找到如下几种状态,拿到当前状态值之后,只需要对比各种状态的值,就知道热点的开启状态了

@return One of 
{@link #WIFI_STATE_DISABLED},
{@link #WIFI_STATE_DISABLING}, 
{@link #WIFI_STATE_ENABLED},
{@link #WIFI_STATE_ENABLING},
{@link #WIFI_STATE_UNKNOWN}

2.通过反射获取到热点的SSID

try {
    WifiManager manager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    //拿到getWifiApConfiguration()方法
    Method method = manager.getClass().getDeclaredMethod("getWifiApConfiguration");
    //调用getWifiApConfiguration()方法,获取到 热点的WifiConfiguration
    WifiConfiguration configuration = (WifiConfiguration) method.invoke(manager);
    ssid = configuration.SSID;
} catch (NoSuchMethodException e) {
    e.printStackTrace();
} catch (InvocationTargetException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
}

你可能感兴趣的:(android)