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/

10-12 04:36