android 开启wifi热点api

2016-3-13 aqi_wolf android

android默认开启wifi热点方式只能通过设置-移动网络共享-便携式wlan热点,为了开启一个热点要进行3部操作,实属麻烦!

因此通过网上查资料,实现wifi热点的一键启动!

通过google获知,android把wifi相关的api给隐藏了,因此只能通过反射机制进行调用!

  /**

    * Start AccessPoint mode with the specified

    * configuration. If the radio is already running in

    * AP mode, update the new configuration

    * Note that starting in access point mode disables station

    * mode operation

    * @param wifiConfig SSID, security and channel details as

    *        part of WifiConfiguration

    * @return {@code true} if the operation succeeds, {@code false} otherwise

    *

    * @hide Dont open up yet

    */

   public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {

       try {

           mService.setWifiApEnabled(wifiConfig, enabled);

           return true;

       } catch (RemoteException e) {

           return false;

       }

   }

配置AP的选项是属于wifi管理的一部分!获取当前系统wifi实例的方式如下:

WifiManger manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

获取当前ap状态的方式如下:

public Boolean getApState() {

    Boolean bApState = FALSE;

    try {

             Method method = manager.getClass().getMethod("isWifiApEnabled");

             bApState = (Boolean)method.invoke(manager);

     } catch (Exception e) {

        e.printStackTrace();

         bApState = FALSE;

    }

    return bApState;

}

配置ap使用的类为:WifiConfiguration //本例直接采用默认配置好的

public WifiConfiguration getApConfiguration() {

    WifiConfiguration apConfigure = new WifiConfiguretion();

    return apConfigure;

}

      使能ap方式如下:

public void setWifiAp(Boolean bOpen) {

    if (bOpen) {

        if (getApState()) {

            return;

        }

        manager.setWifiEnabled(false);

    }

    try {

       Method method = manager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);

       method.invoke(manager, getApConfiguration()/*采用默认的配置,则置为null*/, bOpen);

    } catch (Exception e) {

        e.printStackTrance();

    }

}

源码已上传到github:https://github.com/aqi/WifiAssistant

标签: android wifiAp

发表评论:

Powered by EMLOG Copyright @ 深圳市炽旗科技 版权所有. 闽ICP备14012694号-2