【发布时间】:2017-03-29 11:40:03
【问题描述】:
我有一个应用程序可以通过 wifi direct 与另一部手机(使用相同的应用程序)通信,并且两部手机都必须与蓝牙桥建立连接。当两个设备都有蓝牙连接时,我想启动一个倒数计时器。
我的问题。
我正在使用两个布尔值:
private final AtomicBoolean cnoadv = new AtomicBoolean(false);//represents the other user connection
boolean conexao = false ;// represents my connection
当我的连接完成时,布尔值为“conexao”为真,我启动方法“verificar”以验证两个连接并将“pronto”发送给其他用户,以便他知道我已连接:
conexao = true;
verificar();
chatManager.write("pronto".getBytes());
在其他用户端,当我收到消息“pronto”时,表示其他用户连接的布尔值“cnoadv”变为真,并启动方法“verificar”
public void pushMessage(String readMessage) {
if(readMessage.equals("pronto")){
Log.d("recebido", "pronto");
cnoadv.getAndSet(true);
verificar();
}
验证两个连接的我的 verificar() 方法:
public void verificar() {
if ( cnoadv && conexao) { // error here saying i cant use "&&" in atomic boolean
Toast.makeText(getActivity().getApplicationContext(), "both connections done", Toast.LENGTH_SHORT).show();
}}
我的问题:在验证两个连接的“verificar()”方法中,我想检查两个布尔值是否为真。我该怎么做呢 ?我以错误的方式进行此验证?由于我没有经验,我会感谢一个好的但尽可能简单的解释,非常感谢。
【问题讨论】:
-
对两个 AtomicBoolean 变量使用 get 方法。例如a.get() && b.get()
-
只有“cnoadv”是原子的,“conexao”不是。
标签: java android synchronization boolean atomic