我希望在Android应用中实现更高的网络连接正常运行时间。当用户处于WiFi覆盖的边缘时,电话将失去连接。我的应用程序检测到这一点。
当用户再次进入覆盖范围时,有时需要很长时间(几分钟)才能重新建立与网络的连接。在Android WiFi管理器中,它有时会在切换到“已连接”之前长时间处于“已断开连接”状态(而非“关闭”状态)。该网络是标准的WPA2网络。
我尝试过这样的事情。每次连接丢失时,外部类都会执行ConnectionExecuter。
private void saveConnectionInfo() {
connectionInfo = wiFiManager.getConnectionInfo();
}
private class ConnectExecuter extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
//Do not return before WiFi is enabled and connected
while(!wiFiManager.isWifiEnabled() || !connected()) {
try {
logger.debug(TAG, "Enable");
//Checks is WiFi is disabled, and turns it on in that case.
WiFiEnablementManager.assureWiFiEnabled(wiFiManager);
Thread.sleep(2500);
//if WiFi is not connected then connect to the previous network
logger.debug(TAG, wiFiManager.getConnectionInfo().toString());
if(!connected()) {
logger.debug(TAG, "Reconnecting to network id: " + connectionInfo);
wiFiManager.enableNetwork(connectionInfo.getNetworkId(), true);
wiFiManager.reconnect();
}
Thread.sleep(3000);
} catch (InterruptedException e) {
logger.error(TAG, e);
}
}
return null;
}
private boolean connected() {
if (wiFiManager.getConnectionInfo() != null && connectionInfo != null) {
return wiFiManager.getConnectionInfo().getNetworkId() == connectionInfo.getNetworkId();
}
return false;
}
}
public class WiFiEnablementManager {
public static final ILogger logger = new Logger(WiFiEnablementManager.class.getSimpleName());
public static void assureWiFiEnabled(WifiManager wifiManager) {
if(!wifiManager.isWifiEnabled()){
logger.info("WiFi status disabled: Enabling...");
wifiManager.setWifiEnabled(true);
}
}
}
它似乎对Android 2.2有帮助,但在4.0上无效。睡眠语句(2500毫秒和3000毫秒)也可能不合理。欢迎任何投入。