I want to do something when the wifi connection is established. I have a BroadcastReceiver that works prefectly receiving NETWORK_STATE_CHANGED_ACTION and SCAN_RESULTS_AVAILABLE_ACTION, but not SUPPLICANT_CONNECTION_CHANGE_ACTION. This one is harder to test: I turn off/on the router for that.
protected void onCreate(Bundle savedInstanceState) {
receiverWifi = new WifiReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(receiverWifi, intentFilter);
//...
}
class WifiReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
final String action = intent.getAction();
Log.d("mhp","*BroadcastReceiver: " + action")}
And the Manifiest.xml
<application
a..
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.net.wifi.SCAN_RESULTS" />
<action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
<action android:name="android.net.wifi.STATE_CHANGE" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
And the AndroidManifest.xml:
<application
a..
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.net.wifi.SCAN_RESULTS" />
<action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
<action android:name="android.net.wifi.STATE_CHANGE" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
On connecting to wifi network even if you don't get SUPPLICANT_CONNECTION_CHANGE_ACTION
, you will definitely get NETWORK_STATE_CHANGED_ACTION
and you can play with this action for all your needs.
In the broadcast receiver, do this:
String action = intent.getAction();
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action))
{
NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if ( (netInfo.getDetailedState()==(NetworkInfo.DetailedState.CONNECTED)) )
{
// your wifi is connected, do what you want to do
}
}