从 onReceive() 中调用 notification() ?
所以我试图编写一小段 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上你正在等待线程对象,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.