Broadcast to change WIFI

In my application, I need to receive notifications when the device connects or disconnects from the WIFI network. For this I have to use BroadcastReceiver , but after reading various articles and questions here on SO, I got a little confused about what Broadcast action I should use for this. In my opinion, I have three options:

To reduce resources, I really want to receive notifications only if the device is CONNECTED on the WIFI network (and it received the IP address) or when the device has DISCONNECTED from one. I don't care about other states like CONNECTING etc.

So, what do you think is the best translational action I should use for this? And do I need to filter events completely (because I get more CONNECTED and DISCONNECTED ) in onReceive ?

EDIT: As I said in the comment below, I think SUPPLICANT_CONNECTION_CHANGE_ACTION will be the best choice for me, but it never starts or is not accepted by my application. Others have the same problem with this broadcast, but there is never a real solution for this (other translations are actually used). Any ideas for this?

+5
source share
2 answers

Try

 @Override protected void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); filter.addAction("android.net.wifi.STATE_CHANGE"); registerReceiver(networkChangeReceiver, filter); } @Override protected void onDestroy() { unregisterReceiver(networkChangeReceiver); super.onDestroy(); } 

and

 BroadcastReceiver networkChangeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (!AppUtils.hasNetworkConnection(context)) { showSnackBarToast(getNetworkErrorMessage()); } } }; 

I use this and it works for me. Hope this helps you.

+1
source

You can go to Powered by WifiManager.NETWORK_STATE_CHANGED_ACTION.

Register the receiver using WifiManager.NETWORK_STATE_CHANGED_ACTION The action, both in the manifest and in the fragment or action that ever suits you.

Cancel receiver:

 @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){ NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); boolean connected = info.isConnected(); if (connected) //call your method } } 
+1
source

Source: https://habr.com/ru/post/1271448/


All Articles