gpt4 book ai didi

java - 等待网络连接

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:21:07 26 4
gpt4 key购买 nike

我需要让我的应用程序等到完全建立 wifi 连接后才能继续运行。我现在有这段代码:

wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 
if(!wifiManager.isWifiEnabled())
{
Toast.makeText(this, "Connecting to wifi network", Toast.LENGTH_SHORT).show();
wifiManager.setWifiEnabled(true);
//wait for connection to be establisihed and only then proceed


}

最佳答案

您可以使用注册的广播接收器:

android.net.conn.CONNECTIVITY_CHANGE

监听状态变化并保持当前状态的变量

更多信息 here


<receiver android:name="your.package.WifiReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>

接收者:

public class WifiReceiver extends BroadcastReceiver {

public static boolean connected = false;

@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager mgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = mgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

connected = networkInfo != null && networkInfo.isConnected();
}
}

public boolean isConnected(){
return connected;
}

关于java - 等待网络连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22712631/

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