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

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

问题描述:

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

Is there an API to turn On/Off the WiFi HotSpot on Android programmatically?

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

What methods should I call to turn it On/Off?

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

UPDATE:There's this option to have the HotSpot enabled, and just turn On/Off the WiFi, but this is not a good solution for me.

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

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

Use the class below to change/check the Wifi hotspot setting:

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

希望这对某人有帮助