繁体   English   中英

Android 9.0 wifi热点API

[英]Android 9.0 wifi hotspot API

我需要在 Android 9.0 (Android P) 中进行哪些 API 调用才能获得 Wifi 热点名称?

public static String getWifiApSSID(Context context) {
        try {
            WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            Method method = manager.getClass().getDeclaredMethod("getWifiApConfiguration");
            WifiConfiguration configuration = (WifiConfiguration) method.invoke(manager);
            if (configuration != null) {
                return configuration.SSID;
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return "";
    }

Android 9.0 返回""

您使用的反射方法getWifiApiConfiguration不适用于 API>=26。 好消息,对于 API>=26,你不需要使用反射。 您可以使用 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);

}
`

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

如果您的设备已植根,您还有另一种选择。

使用此命令启用:

service call connectivity 24 i32 0 i32 1 i32 0 s16 text > /dev/null

在 Android 的官方文档中, startLocalOnlyHotspot方法允许共享内部连接但无法访问互联网。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM