Android Wifi Receiver broadcast late response

295 views Asked by At

I've done this wifi receiver where I want do an action when the wifi is enabled...

public class WifiReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        WifiManager wManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
        if (isWifiEnabled(wManager)) {
           new MyTask().execute();
        }
    }

    public static boolean isWifiEnabled(WifiManager wifi) {
        if (wifi==null) return false;
        if (wifi.getWifiState()!= wifi.WIFI_STATE_ENABLED) return false;
        return true;
    }
}

...and this is my manifest for the receiver...

<receiver android:enabled="true" android:name=".receiver.WifiReceiver" android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
    <intent-filter>
        <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

...but the receiver do the task too late (about 10-60 seconds or much) from the wifi switching.

Where is my error? There is another method to do this without use a Service?

1

There are 1 answers

0
Sivateja.koppineedi On

while registering the receiver use the intent filter as WifiManager.WIFI_STATE_CHANGED_ACTION

 BroadcastReceiver wifiStateChangeReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        final String action = intent.getAction();

        if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
          //your code    
        }
    }
};

you need to register your broadcast receiver in Oncreate or Onstart methods like this

 wifiStateChangeFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    registerReceiver(wifiStateChangeReceiver, wifiStateChangeFilter);

but make sure you are unregistering the receivers after work is done.If you are registering in oncreate() method you need to unRegister() in onDestroy() method.If you are Registering in OnStart() means you need to unregister in OnStop() method.