我已經寫了一個菜單爲多個按鈕的應用程序。其中兩個按鈕觸發兩種獨立的藍牙方法。問題是,在多次快速按下這些按鈕時,應用程序崩潰,因爲每種方法都試圖管理藍牙連接(而另一個可能會關閉該連接)。我試圖在任何方法運行時檢查變量'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回答以獲得更好的處理方法 –