我已经写了一个菜单为多个按钮的应用程序。其中两个按钮触发两种独立的蓝牙方法。问题是,在多次快速按下这些按钮时,应用程序崩溃,因为每种方法都试图管理蓝牙连接(而另一个可能会关闭该连接)。我试图在任何方法运行时检查变量'true'并检查它,但它不起作用。我不确定系统是否在不同的线程中同时运行每种方法,或者是否将方法排入队列。停止方法从执行按钮按
问题是,在另一个方法执行时,我该如何停止按下按钮来运行方法?执行完成后我不需要排队,我只需要将其阻塞即可。
编辑:添加的以下方法之一的代码,如请求(另一个是相同的,两个字符串,这是不相关的在此上下文中的除外):
public void lock(View button_lock) {
if(ok)
return;
if (btAdapter == null) {
Context context = getApplicationContext();
CharSequence text = "Bluetooth not supported!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
return;
}
else if (address == null) {
Context context = getApplicationContext();
CharSequence text = "Please pair your phone with SmartLock.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
return;
}
if (!btAdapter.isEnabled()) {
btAdapter.enable();
ok=true;
}
mHandler.postDelayed(new Runnable() {public void run() {
BluetoothDevice device = btAdapter.getRemoteDevice(address);
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket mmSocket;
try {
mmSocket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
mmSocket.connect();
OutputStream out = mmSocket.getOutputStream();
InputStream in = mmSocket.getInputStream();
out.write("1".getBytes());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
in.close();
out.close();
mmSocket.close();
in = null;
out = null;
mmSocket = null;
} catch (IOException e) {
e.printStackTrace();
}
}}, 1000);
Context context = getApplicationContext();
CharSequence text = "Bike locked!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
mHandler.postDelayed(new Runnable() {public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
btAdapter.disable();
ok=false;
}}, 2000);
}
这不能解决问题,只会拖延行动,这是一个不好的方法来处理这个问题,请参阅@Patrick Michel回答以获得更好的处理方法 –