本文介绍了Android与One Plus上的ESP8266的连接(Android 6.0.1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Android 6.0上的改装在连接到接入点后进行Http调用时出现问题
Retrofit on Android 6.0 has a problem making Http calls after connecting to Access Point
复制步骤:
- 连接到Esp8266接入点
- 对 http://192.168.4.1 进行http调用(esp8266访问点的默认网关)WIFI的IP地址为192.168.4.2
- 它引发以下异常
- Connect to Esp8266 Access Point
- Make an http call to http://192.168.4.1 (Default gateway of esp8266 accesspoint)The IP address of WIFI is 192.168.4.2
- It throws the below exception
我已经在Android 5.1上尝试过相同的功能,并且相同的代码也可以正常工作
I have tried the same on Android 5.1 and the same code works flawlessly
推荐答案
问题
错误ENONET
表示NetworkInfo.isConnected()
返回false
解决方案
产生一个守护进程线程,该线程等待Wifi网络(由ssid
提供)完全"连接(请参见上文),并使用true
(成功连接)或false
(超时)调用您的callback
或错误).
Solution
Spawn a daemon Thread which waits for the Wifi network (given by ssid
) to "fully" connect (see above) and call your callback
with either true
(successfully connected) or false
(timeout or error).
private ConnectivityManager connectivity = ...;
private WifiManager wifi = ...;
private void waitForWifi(final String ssid, final Consumer<Boolean> callback) {
final Thread thread = new Thread(() -> {
for (int i = 0; i < 300; i++) {
final WifiInfo info = wifi.getConnectionInfo();
NetworkInfo networkInfo = null;
for (final Network network : connectivity.getAllNetworks()) {
final NetworkCapabilities capabilities = connectivity.getNetworkCapabilities(network);
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
networkInfo = connectivity.getNetworkInfo(network);
break;
}
}
if (info != null && info.ssid == ssid && networkInfo != null && networkInfo.isConnected()) {
callback.accept(true);
return;
}
Thread.sleep(100);
}
callback.accept(false);
});
thread.setDaemon(true);
thread.start();
}
注释
-
ssid
必须用双引号引起来(请参见wifiConfiguration.SSID
) -
ConnectivityManager.getAllNetworks()
需要权限ACCESS_NETWORK_STATE
-
WifiManager.getConnectionInfo()
需要权限ACCESS_NETWORK_STATE
和ACCESS_COARSE_LOCATION
(运行时权限) ssid
must be enclosed in double quotation marks (seewifiConfiguration.SSID
)ConnectivityManager.getAllNetworks()
requires permissionACCESS_NETWORK_STATE
WifiManager.getConnectionInfo()
requires permissionsACCESS_NETWORK_STATE
andACCESS_COARSE_LOCATION
(runtime permission)
Notes
这篇关于Android与One Plus上的ESP8266的连接(Android 6.0.1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!