如何以编程方式更改 Android 中便携式热点的 SSID?

How do I change the Portable Hotspot's SSID in Android programmatically?

我要更改热点SSID!有人可以帮忙吗?

来自 Android turn On/Off WiFi HotSpot programmatically,这是我切换便携式热点的代码:

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

寻找线索的最佳地点是 AOSP 源代码本身。这是相关部分:http://androidxref.com/4.4_r1/xref/frameworks/base/wifi/java/android/net/wifi/WifiManager.java#1147

以下代码对我有用:

public static boolean setHotspotName(String newName, Context context) { 
    try {
        WifiManager wifiManager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
        Method getConfigMethod = wifiManager.getClass().getMethod("getWifiApConfiguration");
        WifiConfiguration wifiConfig = (WifiConfiguration) getConfigMethod.invoke(wifiManager);

        wifiConfig.SSID = newName;

        Method setConfigMethod = wifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);
        setConfigMethod.invoke(wifiManager, wifiConfig);

        return true;
    }
    catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

不要忘记将以下行添加到您的 AndroidManifest.xml:

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