问题描述
我想验证一个Android设备是否已连接到特定的Wi-Fi(由SSID标识)并且同时具有活动的移动数据网络时遇到一些奇怪的问题.我的问题也有可能与Android 9(SDK 28)有关,因为我没有收到以前使用Android版本的用户的投诉.
I am having some strange issues when I want to verify, whether an Android device is connected to a specific Wi-Fi (identified by SSID) AND it has a MOBILE data network active at the same time.It is also likely that my issue is connected to Android 9 (SDK 28), as I did not get any complaints from users with previous Android versions.
这就是我所拥有的:
这是我的主要方法,应该告诉我设备当前是否已连接到目标Wi-Fi:
This is my main method, that should tell me whether the device is currently connected to it's target Wi-Fi:
public boolean isConnectedToTrackerHotSpot() {
if (isConnectedToWiFi()) {
final String ssid = getConnectedSSID();
if (ssid.startsWith(TRACKER_WIFI_PREFIX)) {
Log.i(TAG, "isConnectedToTrackerHotSpot() --> YEAH, connected to Tracker: " + ssid);
return true;
} else {
Log.d(TAG, "isConnectedToTrackerHotSpot() --> NOT connected to Tracker, but: " + ssid);
return false;
}
}
Log.d(TAG, "isConnectedToTrackerHotSpot() --> NOT connected to any Wi-Fi!");
return false;
}
以下是辅助方法:
检查我们当前是否有Wi-Fi连接:
Check, whether we currently have a Wi-Fi connection:
public boolean isConnectedToWiFi() {
if (!isWifiEnabled()) {
Log.w(TAG, "isConnectedToWiFi(): Wi-Fi is DISABLED");
return false;
}
final WifiInfo wifiInfo = getConnectionInfo();
if (wifiInfo == null) {
Log.w(TAG, "isConnectedToWiFi() --> wifiInfo is null!");
return false;
}
final int networkId = wifiInfo.getNetworkId();
if (networkId == -1) {
Log.d(TAG, "isConnectedToWiFi() --> NOT connected to any Wi-Fi (networkId == -1)");
return false;
}
Log.d(TAG, "isConnectedToWiFi() --> connected to Wi-Fi with networkId: " + networkId);
return true;
}
检查我们是否已连接到任何网络:
Check whether we are connected to any network at all:
public boolean isConnected() {
/*
Returns details about the currently active default data network.
When connected, this network is the default route for outgoing connections.
*/
final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo == null) {
Log.d(TAG, "isConnected() --> getActiveNetworkInfo() == NULL (no network connection)");
return false;
} else {
Log.d(TAG, "isConnected() --> networkInfo.getTypeName() = " + networkInfo.getTypeName());
}
if (networkInfo.isConnectedOrConnecting()) {
return true;
}
Log.w(TAG, "isConnected() --> !networkInfo.isConnectedOrConnecting()");
return false;
}
现在,在我的Broadcastreceiver中,我想在连接到预期的设备后立即处理此案:
Now in my Broadcastreceiver, I want to handle the case as soon as I am connected to the anticipated device:
private BroadcastReceiver connectivityBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (!Objects.equals(intent.getAction(), CONNECTIVITY_CHANGE)) {
Log.d(TAG, "connectivityBroadcastReceiver.onReceive() --> not the intent we are interested in");
return;
}
if (wiFiConnectionManager.isConnectedToTrackerHotSpot()) {
Log.i(TAG, "connectivityBroadcastReceiver.onReceive() --> CONNECTED to Tracker --> fragment.updateUiConnectedToTracker()");
fragment.updateUiConnectedToTracker();
openTrackerSocketConnection();
} else {
// Make sure we only show 1 AlertDialog per CONNECT attempt (= button press)
if (userAwaitsResponse) {
Log.d(TAG, "connectivityBroadcastReceiver.onReceive() --> fragment.updateUiFailedToConnect()");
fragment.updateUiFailedToConnect();
userAwaitsResponse = false;
} else {
Log.d(TAG, "connectivityBroadcastReceiver.onReceive() --> SUPPRESSING UI update (since already done)");
}
}
}
};
但是,当我在装有Android 9的Pixel 3上进行测试并启用了移动网络时,却收到了以下日志:
However, when I test this on a Pixel 3 with Android 9 and let the mobile network enabled, I am getting this log:
D/ConnectDeviceFragment: connectButton --> onClick()
I/WiFiConnectionManager: isWiFiEnabled(): true
I/WiFiConnectionManager: isWiFiEnabled(): true
D/ConnectDeviceFragmentPresenter: connectToTrackersWiFi() --> use existing WifiConfiguration SSID: "TRACKER-pat08" (networkId: 141)
D/ConnectDeviceFragmentPresenter: connectToTrackersWiFi() --> going to disconnect from current network...
I/WiFiConnectionManager: disconnect() success: true
D/ConnectDeviceFragmentPresenter: connectToTrackersWiFi() --> in order to enableNetwork for networkId: 141
I/WiFiConnectionManager: enableNetwork() --> netId: 141 | success: true
D/WiFiConnectionManager: isConnectedToWiFi() --> NOT connected to any Wi-Fi (networkId == -1)
D/WiFiConnectionManager: isConnectedToTrackerHotSpot() --> NOT connected to any Wi-Fi!
D/WiFiConnectionManager: isConnected() --> networkInfo.getTypeName() = MOBILE
I/MainFragmentPresenter: connectivityBroadcastReceiver.onReceive() --> Assuming we have internet...
D/WiFiConnectionManager: isConnectedToWiFi() --> NOT connected to any Wi-Fi (networkId == -1)
D/WiFiConnectionManager: isConnectedToTrackerHotSpot() --> NOT connected to any Wi-Fi!
D/ConnectDeviceFragmentPresenter: connectivityBroadcastReceiver.onReceive() --> fragment.updateUiFailedToConnect()
D/ConnectDeviceFragment: updateUiFailedToConnect() --> creating but not showing yet (status might still change)
D/WiFiConnectionManager: isConnectedToWiFi() --> NOT connected to any Wi-Fi (networkId == -1)
D/WiFiConnectionManager: isConnectedToTrackerHotSpot() --> NOT connected to any Wi-Fi!
D/WiFiConnectionManager: isConnected() --> networkInfo.getTypeName() = MOBILE
I/MainFragmentPresenter: connectivityBroadcastReceiver.onReceive() --> Assuming we have internet...
D/WiFiConnectionManager: isConnectedToWiFi() --> NOT connected to any Wi-Fi (networkId == -1)
D/WiFiConnectionManager: isConnectedToTrackerHotSpot() --> NOT connected to any Wi-Fi!
D/ConnectDeviceFragmentPresenter: connectivityBroadcastReceiver.onReceive() --> SUPPRESSING UI update (since already done)
I/ConnectDeviceFragment: updateUiFailedToConnect() --> run() delayed by: 5000
我做错了什么?我的代码可以在没有启用移动网络的任何设备上正常工作...
What am I doing wrong? My code works fine on any device, that has no mobile network enabled...
我可能已经找到了根本原因:
I might have found the root cause:
boolean openSocketConnection() {
if (isSocketReady()) {
Log.i(TAG, "openSocketConnection() --> isSocketReady() --> return true");
return true;
}
//FIXME: Timeout if Wi-Fi AND mobile network are active --> force open socket on Wi-Fi
try {
socket = new Socket(InetAddress.getByName(SERVER_IP), SERVER_PORT);
outputStream = new DataOutputStream(socket.getOutputStream());
inputStream = new DataInputStream(socket.getInputStream());
Log.i(TAG, "openSocketConnection() --> connection opened and input/output streams created!");
return true;
} catch (IOException e) {
Log.e(TAG, "openSocketConnection() --> IOException!", e);
return false;
}
}
因此,新问题是:如何打开Wi-Fi连接上的套接字(尽管活动网络将是移动网络).因为与我的嵌入式设备的Wi-Fi连接将永远无法连接互联网,所以我仍然需要打开一个插座进行通讯...
So the new question is: how can I open a socket on the Wi-Fi connection (despite the active network will be mobile network). Because the Wi-Fi connection to my embedded device will never have internet, nevertheless I need to open a socket for communication...
任何帮助,不胜感激!
推荐答案
我找到了可以以某种方式使用的解决方案.最后,根本问题是,如果您没有明确说明,Android确实会在默认网络上打开一个套接字.而且默认网络显然始终是具有Internet的网络(这是我很难学的).
I found a solution I can somehow live with. The root problem in the end was that Android does open a socket on the default network, if you don't explicitly tell otherwise. And the default network is apparently always the one which has internet (which I learnt the hard way).
这是我的新解决方案的核心:
So here is the center piece of my new solution:
private Socket getTrackerWiFiSocket() throws SocketException {
final Socket socket;
try {
Log.i(TAG, "getTrackerWiFiSocket() --> TRY getSocketFactory().createSocket()");
socket = getSocketFactory().createSocket(TRACKER_API_ADDRESS, TRACKER_API_PORT);
} catch (IOException e) {
Log.e(TAG, "getTrackerWiFiSocket() --> getSocketFactory().createSocket() produced IOException: ", e);
throw new SocketException(TAG + ".getTrackerWiFiSocket() --> create socket failed!");
}
Log.d(TAG, "getTrackerWiFiSocket() --> socket: " + socket);
return socket;
}
private SocketFactory getSocketFactory() throws SocketException {
if (SDK_INT < 21) {
Log.d(TAG, "getSocketFactory() --> SDK_INT is < 21 --> return SocketFactory.getDefault()");
return SocketFactory.getDefault();
}
/*
On API 21 and later, a socket that is NOT created with the Wi-Fi network's SocketFactory may try
to connect via another network --> we have to make sure that always the Wi-Fi network is chosen
*/
Network wifiNetwork = getWiFiNetwork();
// FIXME: Find a nicer approach
for (int i = 0; i < 10; i++) {
Log.d(TAG, "getSocketFactory() --> getWiFiNetwork() loop: " + i);
if (wifiNetwork == null) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Log.w(TAG, "getSocketFactory() --> getWiFiNetwork() --> error during Thread.sleep");
}
wifiNetwork = getWiFiNetwork();
} else {
Log.i(TAG, "getSocketFactory() --> found Wi-Fi network socket!");
return wifiNetwork.getSocketFactory();
}
}
Log.e(TAG, "getSocketFactory() -> Could not find a suitable SocketFactory --> return default");
throw new SocketException(TAG + ".getSocketFactory() --> could not get a SocketFactory!");
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private Network getWiFiNetwork() {
for (Network network : connectivityManager.getAllNetworks()) {
NetworkInfo info = connectivityManager.getNetworkInfo(network);
// FIXME: Use another (non-deprecated) way to determine whether type is Wi-Fi
if (info != null && info.getType() == TYPE_WIFI) {
Log.d(TAG, "getWiFiNetwork() --> found network with info: " + info);
return network;
}
}
Log.w(TAG, "getWiFiNetwork() --> Could not find the Wi-Fi network!");
return null;
}
如果有人能更好地确定该对象,那么与我正在听的Thread.sleep()
丑陋循环相比,有一个Network
对象可用于从中创建Socket ...
If anyone has a better approach for making sure, that there is a Network
object available to create a Socket from than my ugly loop with Thread.sleep()
I am listening...
这篇关于在Android上同时连接到MOBILE时如何检查Wi-Fi连接(SSID)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!