我有一个LinkedBlockingQueue
在我的“生产者-调解者-消费者”模型中的调解者中。 Producer 首先更新将 Mediator 添加到 ActivityQueue 中。接下来,消费者/活动在队列中等待/侦听并获取下一个项目。
我想要一个活动来查看队列大小已更改并获取下一个项目。调解员无法了解活动只有活动才能看到中介者。那么我该如何创建我想要的这个监听器机制呢?
这是我的中介类,它保存队列,活动将以某种方式查看队列并获取通知是否需要更新。进入队列的数据有时可能是不稳定且随机的,因此轮询机制将不起作用。
public class MediatorData {
/** Queue for the Activity */
LinkedBlockingQueue <byte[]> queueConsumer = new LinkedBlockingQueue <byte[]>();
/**
* Add data to a queue(s) for consumption
*/
public void put(byte[] data) throws InterruptedException {
queueConsumer.add(data);
}
/**
* Return data from the queue for the Feature calculations
*/
public byte[] getFeatureData() throws InterruptedException {
return queueConsumer.poll(100, TimeUnit.MILLISECONDS);
}
}
我的活动类的示例,它是一个图形类,因此队列侦听器必须高效且快速。
public class DisplayGraph extends Activity {
// populated from Application Class where its created
pirvate MediatorData md;
public void onCreate(Bundle savedInstanceState) {
md = getMediator(); // This comes from the custom Application class
... some type of listener to queue
}
private void getQueueData() {
byte[] tv = md.queueConsumer.poll();
// can't update textview get exception CalledFromWrongThreadException
((TextView) DisplayGraph.this.findViewById(R.id.tv)).setText("TV " + tv[0]);
}
}
怎么样使用Observer http://developer.android.com/reference/java/util/Observer.html and 可观察的 http://developer.android.com/reference/java/util/Observable.html?
可能是这样的:
public class MediatorData extends Observable {
/** Queue for the Activity */
LinkedBlockingQueue <byte[]> queueConsumer = new LinkedBlockingQueue <byte[]>();
/**
* Add data to a queue(s) for consumption
*/
public void put(byte[] data) throws InterruptedException {
queueConsumer.add(data);
setChanged();
notifyObservers();
}
/**
* Return data from the queue for the Feature calculations
*/
public byte[] getFeatureData() throws InterruptedException {
return queueConsumer.poll(100, TimeUnit.MILLISECONDS);
}
}
和这个:
public class DisplayGraph extends Activity implements Observer {
// populated from Application Class where its created
private MediatorData md;
public void onCreate(Bundle savedInstanceState) {
md = getMediator(); // This comes from the custom Application class
md.addObserver(this);
}
private void getQueueData() {
byte[] tv = md.queueConsumer.poll();
// can't update textview get exception CalledFromWrongThreadException
((TextView) DisplayGraph.this.findViewById(R.id.tv)).setText("TV " + tv[0]);
}
public void update(Observable arg0, Object arg1) {
getQueueData();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)