複数のボタンがあるアプリケーションのメニューを作成しました。これらのボタンのうちの2つは、2つの別々のBluetoothメソッドを起動します問題は、これらのボタンを複数回押すと、それぞれのメソッドがBluetooth接続を管理しようとしているため(別の接続がその接続を閉じるかもしれない)、アプリケーションがクラッシュすることです。いずれかのメソッドが実行されていることを確認している間に、変数 '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の対処方法はこちら –