-3

I have a problem with this code it seams that it is working async and it returns false but too late because the code in the if statement seams to run before the check is completed in onReceve.

How can i make the check in onReceve finish first an then run the code in the if statement?

class WifiReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context c, Intent intent) {
        String action  = intent.getAction();
        if(action.equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)){
            Log.d("WifiReceiver", ">>>>SUPPLICANT_STATE_CHANGED_ACTION<<<<<<");
            int supl_error=intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, -1);
            if(supl_error==WifiManager.ERROR_AUTHENTICATING){
                Log.i("ERROR_AUTHENTICATING", "ERROR_AUTHENTICATING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                flag = false;
            }
            else {
                flag = true;
            }
        }
    }
}

if(flag){
//do something
}
shotofop
  • 11
  • 4
  • already answered in many, many similar questions: by putting `if` inside `onReceive` – Selvin Oct 04 '17 at 13:13
  • i have tried that but the code in the if needs to be run in a different place for the app to work properly – shotofop Oct 04 '17 at 13:16
  • I'm pretty sure your code will not even compile, because you have an inner class changing local variable, and local variables need to be final if they are used by inner classes (including lambdas, but that's beside the point). You may have gotten around it by declaring `flag` as a class field, but you will not get around from requirement that your code that's concerned with the flag needs to be called from somewhere inside `onReceive` method. – M. Prokhorov Oct 04 '17 at 13:22
  • Why did you *expect* that your `if` statement to wait for your async call to finish before running? Isn't that kind of the point of async in the first place? – EJoshuaS - Stand with Ukraine Oct 04 '17 at 13:29
  • yes i want the if statement to wait and i wasn't sure that it was an async – shotofop Oct 04 '17 at 13:40

1 Answers1

1

You put the code you want to call after the Async completes into a method and call the method in onReceive().

mal
  • 3,022
  • 5
  • 32
  • 62
  • i think onReceive() is doing async i dont have any async code i just want the if statement to wait for the check in the onReceve() – shotofop Oct 04 '17 at 13:56
  • Yes. The 'onRecieve' call is the hook that let's you know that it has completed correctly. That's where you call the code you want to trigger afterwards. Try it! – mal Oct 04 '17 at 14:02
  • If the code you're running requires parameters returned by 'onRecieve' then you need to call it from there. – mal Oct 04 '17 at 14:09