使用java代码启用便携式Wi-Fi热点

时间:2013-05-08 08:19:55

标签: android wifi

目前我正在为我的Android手机构建一个非常小的本机应用程序。当我点击应用程序中的一个按钮时,我想激活便携式Wi-Fi热点。但我不知道如何调用Android API到活动的便携式Wi-Fi热点。我知道如何通过UI完成它。有人能告诉我吗?

1 个答案:

答案 0 :(得分:0)

// code to enable portable wifi hotspot
public void EnableWifiHotspot(){
  try{
      WifiManager wifi_manager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
          WifiConfiguration wifi_configuration = null;


          Method wifiHotspotEnabledMethod=wifi_manager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
          wifiHotspotEnabledMethod.invoke(wifi_manager, wifi_configuration, true);
   }
   catch (NoSuchMethodException e) 
      {

         e.printStackTrace();

      } 
      catch (IllegalArgumentException e) 
      {

         e.printStackTrace();

      } 
      catch (IllegalAccessException e) 
      {

         e.printStackTrace();

      } 
      catch (InvocationTargetException e) 
      {

         e.printStackTrace();

      }

}

//code for disabling portable wifi hotspot
 public void DisableWifiHotspot(){
  try{
      WifiManager wifi_manager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
          WifiConfiguration wifi_configuration = null;


          Method wifiHotspotEnabledMethod=wifi_manager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
          wifiHotspotEnabledMethod.invoke(wifi_manager, wifi_configuration, false);
   }
   catch (NoSuchMethodException e) 
      {

         e.printStackTrace();

      } 
      catch (IllegalArgumentException e) 
      {

         e.printStackTrace();

      } 
      catch (IllegalAccessException e) 
      {

         e.printStackTrace();

      } 
      catch (InvocationTargetException e) 
      {

         e.printStackTrace();

      }

}