我正在使用以下代码连接到没有互联网连接的WiFi网络,因为它拥有自己的网络服务器,我想连接即使没有互联网连接.
WifiConfiguration wifiConfiguration = new WifiConfiguration(); wifiConfiguration.SSID = String.format("\"%s\"",scanResult.SSID); wifiConfiguration.preSharedKey = String.format("\"%s\"","secret"); int netId = wifiManager.addNetwork(wifiConfiguration) wifiManager.disconnect(); wifiManager.enableNetwork(netId,true); wifiManager.reconnect();
这适用于Android Marshmallow下面的每个设备(我使用CM13,所以它可能与CyanogenMod有关?):当我使用此代码连接时,Android仍然使用移动连接并用感叹号标记WiFi符号.几秒钟之后它会显示一个问题通知我是否要保持连接,因为网络没有互联网连接.
问题:我的应用尝试自动连接到我的网络服务器失败,因为显然没有互联网连接.当然可以等到我能够访问我的网络服务器,但它应该在没有用户交互的情况下工作.
解决方法
我通过绑定(connectivityManager.bindProcessToNetwork(network);)将当前进程绑定到连接的网络来解决这个问题.这可以防止“继续使用此网络”对话框,并允许您通过wifi与设备通信.
NetworkRequest.Builder builder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder = new NetworkRequest.Builder(); //set the transport type do WIFI builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI); connectivityManager.requestNetwork(builder.build(),new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (Build.VERSION.RELEASE.equalsIgnoreCase("6.0")) { if (!Settings.System.canWrite(mActivity)) { Intent goToSettings = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS); goToSettings.setData(Uri.parse("package:" + mActivity.getPackageName())); mActivity.startActivity(goToSettings); } } connectivityManager.bindProcessToNetwork(null); if (mSsid.contains("my_iot_device-xxxxxxxxx")) { connectivityManager.bindProcessToNetwork(network); } else { } } else { //This method was deprecated in API level 23 ConnectivityManager.setProcessDefaultNetwork(null); if (mSsid.contains("my_iot_device-xxxxxxxxx")) { ConnectivityManager.setProcessDefaultNetwork(network); } else { } } try { //do a callback or something else to alert your code that it's ok to send the message through socket now } catch (Exception e) { Crashlytics.logException(e); e.printStackTrace(); } connectivityManager.unregisterNetworkCallback(this); } }); }