从 onReceive() 中调用 notification() ?

发布于 2025-01-08 07:34:13 字数 746 浏览 5 评论 0原文

所以我试图编写一小段 android 代码,我希望一个线程 A 等待()直到网络连接可用。线程 A 应该做一些与 wifi 相关的事情,因此 BroadcastReceiver 是使用 WifiManager.NETWORK_STATE_CHANGED_ACTION 意图注册的。我现在正在做的是这样的:

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

BroadcastReceiver 的 onReceive() 方法:

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

目前我收到错误:“在通知之前对象未被线程锁定。”我真的不知道如何让这个东西工作...我想另一种选择是用小的 Thread.sleep(#) 围绕 networkReady 标志旋转,但这看起来确实不像对我来说很好的做法;)有什么想法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如歌彻婉言 2025-01-15 07:34:13

实际上你正在等待线程对象,wait();意味着 this.wait();但在通知期间,您正在通知接收者对象。所以你会收到错误。尝试在同一个对象上等待和通知,例如 networkReady 本身。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文