Android以编程方式打开/关闭WiFi HotSpot

mxg*_*mxg 53 android wifi android-wifi

是否有API以编程方式打开/关闭Android上的WiFi HotSpot?

我应该用什么方法打开/关闭它?

更新:有这个选项可以启用HotSpot,只需打开/关闭WiFi,但这对我来说不是一个好的解决方案.

Ash*_*ahu 52

使用下面的类更改/检查Wifi hotspot设置:

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;
}
} // end of class
Run Code Online (Sandbox Code Playgroud)

您需要将以下权限添加到AndroidMainfest:

<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" />
Run Code Online (Sandbox Code Playgroud)

从任何地方使用此独立的ApManager类,如下所示:

ApManager.isApOn(YourActivity.this); // check Ap state :boolean
ApManager.configApState(YourActivity.this); // change Ap state :boolean
Run Code Online (Sandbox Code Playgroud)

希望这会对某人有所帮助

  • 谢谢.我必须添加以下权限才能使其在Android 6上运行:`<uses-permission android:name ="android.permission.WRITE_SETTINGS"/>` (2认同)
  • 这在Android 6+中不再有效.请参见此处:http://stackoverflow.com/a/35504709/4307173.而不是ACTION_SETTINGS,使用ACTION_PICK_WIFI_NETWORK (2认同)
  • @KenKenKen 这是错误的,我刚刚在带有 7.1.1 的 Nexus 5X 上进行了测试,但是您必须授予“WRITE_SETTINGS”权限,该权限要求用户专门接受。 (2认同)

Com*_*are 8

Android SDK中没有与WiFi热点功能相关的方法 - 抱歉!

  • 道歉.这些应用程序如何打开呢? (11认同)
  • @aloneguid:"那不是真的" - 是的,确实如此."adroid市场上的应用程序开启了wifi hostspot,并且它们不需要生根" - 这与我的回答无关.Android SDK中没有与WiFi热点功能相关的方法,至少截至撰写本文时为止. (5认同)
  • 这不是真的,adroid市场上的应用程序开启了wifi hostspot,而且它们不需要生根 (2认同)

小智 7

如果您想在您的 android 应用程序中以编程方式实现 wifi 热点功能,这里是完整的解决方案。

API < 26 的解决方案:

对于< API 26 的设备。Android 没有为此目的提供公共 API。因此,为了使用这些 API,您必须通过反射访问私有 API 。不推荐这样做,但如果您没有其他选择,那么这里有一个技巧。

首先,您需要在清单中拥有此权限,

  <uses-permission  
  android:name="android.permission.WRITE_SETTINGS"  
  tools:ignore="ProtectedPermissions"/>

  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Run Code Online (Sandbox Code Playgroud)

以下是您在运行时询问它的方法:

 private boolean showWritePermissionSettings() {    
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M  
    && Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { 
  if (!Settings.System.canWrite(this)) {    
    Log.v("DANG", " " + !Settings.System.canWrite(this));   
    Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS); 
    intent.setData(Uri.parse("package:" + this.getPackageName()));  
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    this.startActivity(intent); 
    return false;   
  } 
}   
return true; //Permission already given 
}
Run Code Online (Sandbox Code Playgroud)

然后您可以setWifiEnabled通过反射访问该方法。如果您要求的操作正在正确处理,即启用/禁用热点,则返回 true。

     public boolean setWifiEnabled(WifiConfiguration wifiConfig, boolean enabled) { 
 WifiManager wifiManager;
try {   
  if (enabled) { //disables wifi hotspot if it's already enabled    
    wifiManager.setWifiEnabled(false);  
  } 

   Method method = wifiManager.getClass()   
      .getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);   
  return (Boolean) method.invoke(wifiManager, wifiConfig, enabled); 
} catch (Exception e) { 
  Log.e(this.getClass().toString(), "", e); 
  return false; 
}   
}
Run Code Online (Sandbox Code Playgroud)

您还可以通过反射获取热点的wifi配置。我已经在 StackOverflow 上回答了这个问题的方法。

PS:如果您不想以编程方式打开热点,您可以启动此意图 并打开 wifi 设置屏幕供用户手动打开它。

API >= 26 的解决方案:

最后,android 发布了版本 >= Oreo 的官方 API。您可以使用 android 公开的 API,即startLocalOnlyHotspot

它会在没有互联网访问的情况下打开本地热点。因此可用于托管服务器或传输文件。

它需要Manifest.permission.CHANGE_WIFI_STATEACCESS_FINE_LOCATION权限。

这是一个简单的示例,说明如何使用此 API 打开热点。

private WifiManager wifiManager;
WifiConfiguration currentConfig;
WifiManager.LocalOnlyHotspotReservation hotspotReservation;
Run Code Online (Sandbox Code Playgroud)

开启热点的方法:

@RequiresApi(api = Build.VERSION_CODES.O)
public void turnOnHotspot() {

      wifiManager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {

        @Override
        public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
          super.onStarted(reservation);
          hotspotReservation = reservation;
          currentConfig = hotspotReservation.getWifiConfiguration();

          Log.v("DANG", "THE PASSWORD IS: "
              + currentConfig.preSharedKey
              + " \n SSID is : "
              + currentConfig.SSID);

          hotspotDetailsDialog();

        }

        @Override
        public void onStopped() {
          super.onStopped();
          Log.v("DANG", "Local Hotspot Stopped");
        }

        @Override
        public void onFailed(int reason) {
          super.onFailed(reason);
          Log.v("DANG", "Local Hotspot failed to start");
        }
      }, new Handler());
    }
`
Run Code Online (Sandbox Code Playgroud)

以下是获取本地创建的热点的详细信息的方法

private void hotspotDetaisDialog()
{

    Log.v(TAG, context.getString(R.string.hotspot_details_message) + "\n" + context.getString(
              R.string.hotspot_ssid_label) + " " + currentConfig.SSID + "\n" + context.getString(
              R.string.hotspot_pass_label) + " " + currentConfig.preSharedKey);

}
Run Code Online (Sandbox Code Playgroud)

如果它抛出一个安全异常,即使在授予所需的权限后,您也应该尝试使用 GPS 启用您的位置。这是解决方案

最近,我开发了一个名为Spotserve的演示应用程序。这会为 API>=15 的所有设备打开 wifi 热点,并在该热点上托管一个演示服务器。您可以查看更多详细信息。希望这可以帮助!


jos*_*ndo 1

您最好的选择是查看 WifiManager 类。具体setWifiEnabled(bool)功能。

请参阅文档: http://developer.android.com/reference/android/net/wifi/WifiManager.html#setWifiEnabled(boolean)

有关如何使用它的教程(包括您需要什么权限)可以在这里找到: https://web.archive.org/web/20210228070142/http ://www.tutorialforandroid.com/2009/10/turn-off -打开-wifi-in-android-using.html


归档时间:

查看次数:

91297 次

最近记录:

5 年,11 月 前