在安卓奥利奥8.x中更改WiFi热点的SSID和密码

在我的Android应用程序中,我使用以下代码片段:

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

    manager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback(){

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

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

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

这段代码会创建一个名为“AndroidShare_1234”的热点。对于我的一个项目,我需要能够为这个热点设置密码和SSID,但是我找不到这样做的方法。我想创建一个带有SSID和自定义密码的热点。MyHotspot

请注意,Android O中不再支持,这就是在旧版本的Android中完成的方式。但是,我仍然需要以编程方式使用SSID和密码创建wifi热点。我不知道该怎么做。提前致谢!setWifiApEnabled

对于谁在乎...:

对于一个学校项目,我做了一个储物柜,只要它可以连接到具有某些关键因素的无线网络,它就会解锁,因此需要以编程方式设置热点。


答案 1

我对这个问题只有部分解决方案。希望它对于您正在设计的应用程序来说已经足够了。

当您启动热点时,SSID和密码由Android系统硬编码。通过查看AOSP代码,我看到多个应用程序可以共享相同的热点。此热点的配置(类名是 )也与所有请求应用程序共享。此配置将在回调中传递回应用程序。您可以通过致电 .您将从对象中获取所需的所有信息。因此,您可以读取预共享密钥和接入点名称。但是我不认为您可以更改它们


FYI,设置wifi配置的相关代码(包括硬编码的SSID和WPA2-PSK密钥)由以下代码完成WifiConfigurationonStarted(LocalOnlyHotspotReservation reservation)WifiConfigurationreservation.getWifiConfiguration()WifiConfiguration

  /**
   * Generate a temporary WPA2 based configuration for use by the local only hotspot.
   * This config is not persisted and will not be stored by the WifiApConfigStore.
   */
   public static WifiConfiguration generateLocalOnlyHotspotConfig(Context context) {
       WifiConfiguration config = new WifiConfiguration();
       config.SSID = context.getResources().getString(
              R.string.wifi_localhotspot_configure_ssid_default) + "_"
                      + getRandomIntForDefaultSsid();
       config.allowedKeyManagement.set(KeyMgmt.WPA2_PSK);
       config.networkId = WifiConfiguration.LOCAL_ONLY_NETWORK_ID;
       String randomUUID = UUID.randomUUID().toString();
       // first 12 chars from xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
       config.preSharedKey = randomUUID.substring(0, 8) + randomUUID.substring(9, 13);
       return config;
   }

答案 2

推荐