java - 在 Android Oreo 8.x 中更改 WiFi 热点的 SSID 和密码

标签 java android android-wifi android-8.0-oreo hotspot

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

@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,但是我找不到这样做的方法。我想用 MyHotspot 之类的 SSID 和自定义密码创建一个热点。

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

谁在乎...:

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

最佳答案

我对这个问题只有部分解决方案。希望它足以满足您正在设计的应用程序。

启动热点时,SSID 和密码由安卓系统硬编码。通过查看 AOSP 代码,我发现同一个热点可以由多个应用程序共享。此热点的配置(类名是 WifiConfiguration)也与所有请求应用程序共享。此配置在回调 onStarted(LocalOnlyHotspotReservation reservation) 中传递回应用程序。您可以通过调用 reservation.getWifiConfiguration() 获取 WifiConfiguration。您将从 WifiConfiguration 对象中获得所需的所有信息。因此您可以读取预共享 key 和接入点名称。但我不认为你可以改变它们


仅供引用,设置 wifi 配置的相关代码(包括硬编码的 SSID 和 WPA2-PSK key )由以下代码完成

  /**
   * 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;
   }

关于java - 在 Android Oreo 8.x 中更改 WiFi 热点的 SSID 和密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47700717/

相关文章:

java - 如何制作用于展开和折叠的递归 onClickListener?

安卓布局问题

android - 如何通过旋转正确保留 DialogFragment?

android - 监听WIFI状态

java - 可恢复的 XML 解析

java - 设置 throwExceptionIfNoHandlerFound 在 Spring 4.2 中无效。*

java - 使用 servlet 时的 Tomcat 404

java - 在测试项目中找不到从方法 y 引用的类 x

java - WifiP2pGroup - 重新启动持久组?

android - 如何在android中设置安全热点(带密码)