gpt4 book ai didi

java - 一旦 Android 应用程序检测到特定的 Wi-Fi 网络,就会触发一些代码

转载 作者:行者123 更新时间:2023-11-30 09:08:13 25 4
gpt4 key购买 nike

我正在开发一个 Android 应用程序。要使此应用正常运行,需要始终启用 Wi-Fi。由于启用了 Wi-Fi,它将继续扫描可用网络。

我希望在 Wi-Fi 连接到特定网络后立即调用某些函数。我如何实现这一点?

我已经写了下面的代码,但它只工作了一次,我该如何连续扫描网络?

ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(wifi.isConnected()){
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null && !(connectionInfo.getSSID().equals(""))) {
String ssid = connectionInfo.getSSID();
}
Log.i("wifi", "connected");
}
else{
Log.i("wifi", "not connected");
}

最佳答案

跟着步骤做个把戏

1) 创建NetworkChangeReceiver

public class NetworkChangeReceiver extends BroadcastReceiver {

public static boolean isWifiConnected = true;
public static final String tag = "NETWORKCHANGERECEIVER";

@Override
public void onReceive(final Context context, final Intent intent) {

ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifi.isConnected()) {
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null && !(connectionInfo.getSSID().equals(""))) {
String ssid = connectionInfo.getSSID();
}
isWifiConnected = true;
Log.i("wifi", "connected");
} else {
Log.i("wifi", "not connected");
isWifiConnected = false;
}
}
}

2) 将此行添加到 Manifest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

<receiver android:name="com.df.src.NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>

关于java - 一旦 Android 应用程序检测到特定的 Wi-Fi 网络,就会触发一些代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23670295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com