【问题标题】:How do I enable/disable hotspot or tethering mode programmatically on Android?如何在 Android 上以编程方式启用/禁用热点或网络共享模式?
【发布时间】:2021-04-29 13:49:01
【问题描述】:

我在 Android 的网站上看到很多引用 local Only Hotspot

但是,我需要从后台服务以编程方式管理蜂窝热点,就像我可以从下拉菜单中手动操作一样。

这曾经是这样的:

method = wifiManager.getClass().getDeclaredMethod("setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
method.invoke(wifiManager, wifiConfiguration, activated);

但此功能已被弃用。

我的无线提供商 (AT&T) 正试图根据连接的设备和方式向我收取不同的费用。网络应该与设备无关,只需将我的数据包传输到它们的目的地。我希望这无关紧要,但我担心我们会失去对设备的控制。

Android 真的不提供简单的 API 调用来管理热点吗?

【问题讨论】:

    标签: java android android-wifi wifimanager android-developer-api


    【解决方案1】:

    如果使用 Android 版本 >= 11

    您可以使用TetheringManager#startTethering 代码here 启动热点。这是官方文档中关于使用的example

    同样,有一个TetheringManager#stopTethering 方法,代码为here。这将停止热点。

    如果使用 Android 版本

    ConnectivityManager#startTethering 可以与代码详细信息here 一起使用。同样,还有一个ConnectivityManager#stopTethering 方法,代码为here

    【讨论】:

    • 谢谢!我正在尝试测试您的建议并有一个快速的问题。我可以 git clone cs.android.com/android/platform/superproject 吗?这样我就不必重新创建项目中的每个文件,只需导入即可。我在 gitlab 上找到了一面镜子,但它没有网络共享代码。再次感谢。
    • 我发现了这个: git clone android.googlesource.com/kernel/superproject 但它没有让我找到网络共享代码。
    • 您好 Physii,这些是 Android SDK 的 API 的一部分。如果您使用的是 Android,它们应该已经可供您使用。您可以通过使用adb shell service check tethering 进入您的设备来确认tethering 服务是否存在。如果返回Service tethering: found,则您的设备上已经存在所需的服务,只要您的应用拥有@SystempApi 权限,您就可以使用此API。
    • 我收到 Service tethering: not found 我使用的是 Android 版本 9。
    • 感谢 Physii 提供的详细信息。 TetheringManager 在 Android 9 上不可用。我更新了答案,提供了更多详细信息,希望对您有所帮助。
    【解决方案2】:

    因为我不需要互联网而只需要本地热点,我正在使用 startLocalOnlyHotspot 但我正在努力寻找一种可能的解决方案来使用自定义 SSID 和 preSharedKey 启动它,例如 SSID = "testhotspot" 和 preSharedKey = "testhotspot",所以我尝试在 LocalOnlyHotspotCallback 的 onStarted 事件中放入一些代码,但它没有设置它....即使我也尝试使用公共静态 WifiConfiguration generateLocalOnlyHotspotConfig(Context context) :

    public static WifiConfiguration generateLocalOnlyHotspotConfig(Context context){
        WifiConfiguration config = new WifiConfiguration();
        config.SSID = "TESTHOTSPOT";
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        config.networkId = LOCAL_ONLY_NETWORK_ID;
        //String randomUUID = UUID.randomUUID().toString();
        // first 12 chars from xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
        config.preSharedKey = "TESTHOTSPOT";
        return config;
    }
    

    但是这种方式都不起作用...任何方向都将不胜感激...谢谢!干杯!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      • 2011-09-26
      • 2011-06-10
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 2010-10-26
      相关资源
      最近更新 更多