Search code examples
androidmultithreadingbroadcastreceiverwaitnotify

calling notify() from within onReceive()?


so I'm trying to write a small piece of android code where I want one thread, A, to wait() until the network connection becomes available. Thread A is supposed to do some wifi related stuff, and thus the BroadcastReceiver is registered with the intent WifiManager.NETWORK_STATE_CHANGED_ACTION. What I'm doing now is something like this:

Boolean networkReady = new Boolean(false);
...
Thread A {
  synchronized (networkReady) {
    if (!networkReady) {
      wait();
    }
  }
  doStuff();
}
...

BroadcastReceiver's onReceive() method:

public void onReceive(Context context, Intent intent) {
  if (EXTRA_NETOWRK_INFO does show that network is ready) {
    synchronized (networkReady) {
      networkReady = true;
      notify();
    }
  }
}

Currently I'm getting the error: "object not locked by thread before notify." and I can't really figure out how to get this thing to work... One other alternative I guess would be to spin around the networkReady flag with small Thread.sleep(#)'s, but that really doesn't seem like good practice to me ;) Any ideas?


Solution

  • Actually you are waiting on the thread object, wait(); means this.wait(); but during notify you are notifying on the receiver object. so you are getting error. Try to wait and notify on the same object say networkReady itself.