gpt4 book ai didi

java - 每次 wifi 断开时通知

转载 作者:行者123 更新时间:2023-11-30 03:19:38 25 4
gpt4 key购买 nike

我需要我的应用程序在 WiFi 离线时发出通知。

我让它在每次 WiFi 连接发生变化时发出通知。但我需要它只在离线时发出通知。

它还会在(应用程序的)启动时发出通知。

我的问题是,如何更改代码以仅在 WiFi 离线时发出通知?现在它会在离线、在线和启动时发出通知。

代码:

     public class MainActivity extends Activity { 
@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
this.registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
setContentView(R.layout.activity_main);
}

private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

if(currentNetworkInfo.isConnected()){

}else{
showNotification();
}
}
};

最佳答案

像这样尝试:

if(currentNetworkInfo != null &&
currentNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI &&
currentNetworkInfo.getState() == NetworkInfo.State.DISCONNECTING) {
showNotification();
}

还有其他可能的状态(例如 NetworkInfo.State.DISCONNECTED,也许这就是您想要的),您可以在此处找到完整列表: http://developer.android.com/reference/android/net/NetworkInfo.State.html

关于java - 每次 wifi 断开时通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19388575/

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