gpt4 book ai didi

java - 如何获取 WiFi 断开广播的原因

转载 作者:太空宇宙 更新时间:2023-11-04 10:59:46 25 4
gpt4 key购买 nike

我有一个 list 注册的 BroadcastReceiver,用于监控 WiFi 断开连接。每次设备扫描 WiFi 时我都会收到断开连接广播。我需要某种方法来确定广播是扫描 WiFi 的结果还是设备实际上与网络断开连接的结果。

public class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
if(!intent.getAction().equals("android.net.wifi.STATE_CHANGE"))
return;
NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo != null) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
if(networkInfo.getDetailedState() == CONNECTED || networkInfo.getDetailedState() == DISCONNECTED)
PresenceData.loadData(context);
if(networkInfo.getDetailedState() == CONNECTED) {
System.out.println("Wifi connected");
PresenceData.sendNotification("Wifi Connected", "You are now connected to " + PresenceData.getCurrentWifiSSID(context), context);
PresenceData.submitChanges(context);
} else if(networkInfo.getDetailedState() == DISCONNECTED) {
System.out.println("Wifi Disconnected");
PresenceData.sendNotification("Wifi Disconnected", "Your wifi has disconnected", context);
UpdaterService.scheduleUpdate(context);
}
}
}
}
}

最佳答案

您可以尝试使用 NetworkInfo.State获取网络的当前状态。枚举了各种可能的状态,例如失败、成功、扫描等。下面是如何检索信息的示例:

public class MainActivity extends AppCompatActivity {

private ConnectivityManager connectivityManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.connectivityManager = (ConnectivityManager)
this.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
System.out.println("Network Status " + info.getDetailedState().name());
}
}

关于java - 如何获取 WiFi 断开广播的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47018656/

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