70

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

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

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

4

13 回答 13

59

警告此方法在 5.0 之后无法使用,这是一个相当过时的条目。

使用以下类更改/检查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

您需要将以下权限添加到您的 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" />

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

ApManager.isApOn(YourActivity.this); // check Ap state :boolean
ApManager.configApState(YourActivity.this); // change Ap state :boolean

希望这会对某人有所帮助

于 2014-05-14T09:43:00.373 回答
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"/>

这是在运行时询问它的方法:

 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 
}

然后,您可以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; 
}   
}

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

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

API >= 26 的解决方案:

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

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

它需要Manifest.permission.CHANGE_WIFI_STATEACCESS_FINE_LOCATION权限。

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

private WifiManager wifiManager;
WifiConfiguration currentConfig;
WifiManager.LocalOnlyHotspotReservation hotspotReservation;

开启热点的方法:

@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());
    }
`

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

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);

}

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

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

于 2019-08-06T02:27:43.830 回答
4

警告此方法在 5.0 之后无法使用,这是一个相当过时的条目。

您可以使用以下代码以编程方式启用、禁用和查询 wifi 直连状态。

package com.kusmezer.androidhelper.networking;

import java.lang.reflect.Method;
import com.google.common.base.Preconditions;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.util.Log;

public 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;

      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");
      }   
      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;
       }
      }
}
于 2013-05-13T07:12:25.843 回答
4

对于 Android 8.0,有一个新的 API 来处理热点。据我所知,使用反射的旧方法不再起作用。请参阅:

Android 开发者 https://developer.android.com/reference/android/net/wifi/WifiManager.html#startLocalOnlyHotspot(android.net.wifi.WifiManager.LocalOnlyHotspotCallback,%20android.os.Handler)

void startLocalOnlyHotspot (WifiManager.LocalOnlyHotspotCallback callback, 
                Handler handler)

请求一个仅限本地的热点,应用程序可以使用该热点在连接到创建的 WiFi 热点的同位设备之间进行通信。此方法创建的网络将无法访问 Internet。

Stack Overflow
如何在 Android 8.0 (Oreo) 中以编程方式打开/关闭 wifi 热点

onStarted(WifiManager.LocalOnlyHotspotReservation reservation) 方法将在热点打开时被调用。使用 WifiManager.LocalOnlyHotspotReservation 引用调用 close() 方法来关闭热点。

于 2018-01-25T11:29:42.480 回答
2

这对我很有效:

WifiConfiguration apConfig = null;
Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
method.invoke(wifimanager, apConfig, true);
于 2014-02-18T09:02:09.187 回答
2

仅适用于奥利奥+...

在 GitHub 上用代码制作了一个应用程序,它使用反射和DexMaker来“获取”奥利奥的网络共享功能,该功能现在ConnectionManager位于WifiManager.

里面的东西WifiManager只适用于封闭的 wifi 网络(这解释了类名中的 Closed 位!)。

更多解释https://stackoverflow.com/a/49356255/772333

于 2018-03-19T05:29:42.363 回答
2

APManager - 接入点管理器

第 1 步:将 jcenter 存储库添加到您的构建文件
allprojects {
    repositories {
        ...
        jcenter()
    }
}
第二步:添加依赖
dependencies {
    implementation 'com.vkpapps.wifimanager:APManager:1.0.0'
}
第 3 步在您的应用中使用
APManager apManager = APManager.getApManager(this);
apManager.turnOnHotspot(this, new APManager.OnSuccessListener() {

    @Override
    public void onSuccess(String ssid, String password) {
        //write your logic
    }

}, new APManager.OnFailureListener() {

    @Override
    public void onFailure(int failureCode, @Nullable Exception e) {
        //handle error like give access to location permission,write system setting permission,
        //disconnect wifi,turn off already created hotspot,enable GPS provider
        
        //or use DefaultFailureListener class to handle automatically
    }

});

查看源代码 https://github.com/vijaypatidar/AndroidWifiManager

于 2020-11-20T13:46:23.650 回答
1

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

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

关于如何使用它的教程(包括你需要什么权限)可以在这里找到: http ://www.tutorialforandroid.com/2009/10/turn-off-turn-on-wifi-in-android-using.html

于 2011-06-18T07:43:01.517 回答
1

我已经发布了同样的非官方 api,它包含的不仅仅是热点 turn on/off关联

对于 API 的文档链接

于 2014-12-16T08:31:41.510 回答
0

我们可以以编程方式打开和关闭

setWifiApDisable.invoke(connectivityManager, TETHERING_WIFI);//Have to disable to enable
setwifiApEnabled.invoke(connectivityManager, TETHERING_WIFI, false, mSystemCallback,null);

使用回调类,以编程方式打开 pie(9.0) 中的热点,您需要以编程方式关闭并打开开关。

于 2019-04-08T09:23:18.293 回答
0

**对于奥利奥和馅饼**我在下面找到了这个

private WifiManager.LocalOnlyHotspotReservation mReservation;
private boolean isHotspotEnabled = false;
private final int REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS = 101;

private boolean isLocationPermissionEnable() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
        return false;
    }
    return true;
}

@RequiresApi(api = Build.VERSION_CODES.O)
private void turnOnHotspot() {
    if (!isLocationPermissionEnable()) {
        return;
    }
    WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

    if (manager != null) {
        // Don't start when it started (existed)
        manager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {

            @Override
            public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
                super.onStarted(reservation);
                //Log.d(TAG, "Wifi Hotspot is on now");
                mReservation = reservation;
                isHotspotEnabled = true;
            }

            @Override
            public void onStopped() {
                super.onStopped();
                //Log.d(TAG, "onStopped: ");
                isHotspotEnabled = false;
            }

            @Override
            public void onFailed(int reason) {
                super.onFailed(reason);
                //Log.d(TAG, "onFailed: ");
                isHotspotEnabled = false;
            }
        }, new Handler());
    }
}

@RequiresApi(api = Build.VERSION_CODES.O)
private void turnOffHotspot() {
    if (!isLocationPermissionEnable()) {
        return;
    }
    if (mReservation != null) {
        mReservation.close();
        isHotspotEnabled = false;
    }
}

@RequiresApi(api = Build.VERSION_CODES.O)
private void toggleHotspot() {
    if (!isHotspotEnabled) {
        turnOnHotspot();
    } else {
        turnOffHotspot();
    }
}

@RequiresApi(api = Build.VERSION_CODES.O)
private void enableLocationSettings() {
    LocationRequest mLocationRequest = new LocationRequest();
    /*mLocationRequest.setInterval(10);
    mLocationRequest.setSmallestDisplacement(10);
    mLocationRequest.setFastestInterval(10);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);*/
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
    builder.addLocationRequest(mLocationRequest)
            .setAlwaysShow(false); // Show dialog

    Task<LocationSettingsResponse> task= LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());

    task.addOnCompleteListener(task1 -> {
        try {
            LocationSettingsResponse response = task1.getResult(ApiException.class);
            // All location settings are satisfied. The client can initialize location
            // requests here.
            toggleHotspot();

        } catch (ApiException exception) {
            switch (exception.getStatusCode()) {
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    // Location settings are not satisfied. But could be fixed by showing the
                    // user a dialog.
                    try {
                        // Cast to a resolvable exception.
                        ResolvableApiException resolvable = (ResolvableApiException) exception;
                        // Show the dialog by calling startResolutionForResult(),
                        // and check the result in onActivityResult().
                        resolvable.startResolutionForResult(HotspotActivity.this, REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS);
                    } catch (IntentSender.SendIntentException e) {
                        // Ignore the error.
                    } catch (ClassCastException e) {
                        // Ignore, should be an impossible error.
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    // Location settings are not satisfied. However, we have no way to fix the
                    // settings so we won't show the dialog.
                    break;
            }
        }
    });
}

@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
    switch (requestCode) {
        case REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS:
            switch (resultCode) {
                case Activity.RESULT_OK:
                    // All required changes were successfully made
                    toggleHotspot();
                    Toast.makeText(HotspotActivity.this,states.isLocationPresent()+"",Toast.LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    // The user was asked to change settings, but chose not to
                    Toast.makeText(HotspotActivity.this,"Canceled",Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
            break;
    }
}

使用年龄

btnHotspot.setOnClickListenr(view -> {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        // Step 1: Enable the location settings use Google Location Service
        // Step 2: https://stackoverflow.com/questions/29801368/how-to-show-enable-location-dialog-like-google-maps/50796199#50796199
        // Step 3: If OK then check the location permission and enable hotspot
        // Step 4: https://stackoverflow.com/questions/46843271/how-to-turn-off-wifi-hotspot-programmatically-in-android-8-0-oreo-setwifiapen
        enableLocationSettings();
        return;
    }
}

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

implementation 'com.google.android.gms:play-services-location:15.0.1'
于 2018-11-06T06:52:19.807 回答
0

您可以为该选项使用控制台和服务。

我认为你可以解决这个问题。我直接在控制台中做了一个测试并启用热点

我在这篇文章中发现了这一点 是否可以通过终端使用 adb 连接安卓设备?

读取界面后我们可以使用相同的24但需要更多参数

服务呼叫连接 24 i32 0 i32 1 i32 0 s16 随机

于 2019-07-11T15:17:09.797 回答
-3
WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(status);

状态可能是truefalse

添加权限清单:<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

于 2012-08-17T15:55:13.933 回答