每次断开WiFi通知 [英] Notification every time wifi is disconnected

查看:49
本文介绍了每次断开WiFi通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当WiFi离线时,我都需要我的应用程序发出通知.

I need my application to give a notification whenever WiFi goes offline.

每次WiFi连接更改时,我都会发出通知.但是我需要它仅在离线时发出通知.

I got it to give a notification every time the WiFi connection changes. But I need it to only give a notification when it goes offline.

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

Also it gives a notification on start-up (of the application).

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

My question is, how do I alter the code to only give a notification when WiFi goes offline? Now it gives a notification when it goes offline, online and on start-up.

代码:

 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();}

 }
 };

推荐答案

BroadCastReceiver

if(!isNetworkConnectionAvailable(ctx)){
        Toast.makeText(ctx, "Network Connection Available ", Toast.LENGTH_LONG).show();
    }

isNetworkConnectionAvailable()的代码是

the code for isNetworkConnectionAvailable() is

    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;
}

评论我的结果

这篇关于每次断开WiFi通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆