每次wifi断开连接时发出通知

时间:2013-10-16 11:46:55

标签: java android eclipse

我需要我的应用程序在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();}

 }
 };

2 个答案:

答案 0 :(得分:0)

使用此选项检查连接InetAddress.isReachable,如果您有连接,则该方法返回true,否则

答案 1 :(得分:0)

onReceive()

BroadCastReceiver中使用此行
if(!isNetworkConnectionAvailable(ctx)){
        Toast.makeText(ctx, "Network Connection Available ", Toast.LENGTH_LONG).show();
    }

isNetworkConnectionAvailable()的代码是

    public static boolean isNetworkConnectionAvailable(Context context)
{
    boolean isNetworkConnectionAvailable = false;

    ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService("connectivity");
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

    if(activeNetworkInfo != null) 
    {
        isNetworkConnectionAvailable = activeNetworkInfo.getState() == NetworkInfo.State.CONNECTED;
    }
    return isNetworkConnectionAvailable;
}

对结果进行评论