如何通过编程将安卓手机连接到我笔记本上设置的热点?

huangapple go评论66阅读模式
英文:

How to connect an android phone to the hotspot setup on my laptop programmatically?

问题

我正在开发一个Android应用程序,在其中我需要使用Java编程将我的手机连接到我的笔记本电脑热点。情景是,当我在应用程序中点击一个按钮时,我的设备应断开与连接的WiFi网络的连接,并自动连接到我的笔记本电脑热点。我已经实现了将手机与连接的WiFi网络断开连接的代码,但是,我需要知道如何将它特定地连接到笔记本电脑的热点。

英文:

I am developing an Android application in which I need to connect my phone to my laptop hotspot programmatically using Java. The scenario is, when I click a button in the application, my device should disconnect from the connected wifi network and should automatically connect to my laptop hotspot. I have implemented the code to disconnect my phone from the connected wifi network, however, I need to know how should I connect it to the laptop hotspot specifically.

答案1

得分: 1

使用此方法可以连接到特定的WIFI网络

private WifiManager wifiManager;
wifiManager = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
connectToWifi("networkSSID", "networkPassword");

/**
 * 连接到指定的WIFI网络。
 *
 * @param networkSSID     - WIFI网络的SSID
 * @param networkPassword - WIFI密码
 */
private void connectToWifi(final String networkSSID, final String networkPassword) {
    if (!wifiManager.isWifiEnabled()) {
        wifiManager.setWifiEnabled(true);
    }

    WifiConfiguration conf = new WifiConfiguration();
    conf.SSID = String.format("\"%s\"", networkSSID);
    conf.preSharedKey = String.format("\"%s\"", networkPassword);

    int netId = wifiManager.addNetwork(conf);
    wifiManager.disconnect();
    wifiManager.enableNetwork(netId, true);
    wifiManager.reconnect();
}

不要忘记在Manifest文件中添加权限

如何通过编程将安卓手机连接到我笔记本上设置的热点?

有关更多信息,请参阅此博客:wifimanager示例

英文:

Using this method you can connect to a specific WIFI network

 private WifiManager wifiManager;
 wifiManager = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
 connectToWifi("networkSSID", "networkPassword");


 /**
 * Connect to the specified wifi network.
 *
 * @param networkSSID     - The wifi network SSID
 * @param networkPassword - the wifi password
 */
private void connectToWifi(final String networkSSID, final String networkPassword) {
    if (!wifiManager.isWifiEnabled()) {
        wifiManager.setWifiEnabled(true);
    }

    WifiConfiguration conf = new WifiConfiguration();
    conf.SSID = String.format("\"%s\"", networkSSID);
    conf.preSharedKey = String.format("\"%s\"", networkPassword);

    int netId = wifiManager.addNetwork(conf);
    wifiManager.disconnect();
    wifiManager.enableNetwork(netId, true);
    wifiManager.reconnect();
}

Don't forget to add permissions in your Manifest file

如何通过编程将安卓手机连接到我笔记本上设置的热点?

Refer this blog for more info : wifimanager example

huangapple
  • 本文由 发表于 2020年10月3日 18:00:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64182973.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定