英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论