#android #sockets #bluetooth
Вопрос:
Создание приложения, которое должно подключаться к устройству Bluetooth и отправлять/получать информацию. Я использую поток для подключения к разъему Bluetooth и обработчик. Приложение работает бесперебойно, но всякий раз, когда я выбираю устройство, код возвращает исключение подключения. Я перепробовал несколько устройств и проверил, подходит ли UUID. Не могу найти решение в течение нескольких дней, был бы очень признателен за помощь.
Код:
public class MainActivity extends AppCompatActivity { private BluetoothAdapter mybtadapter; private Button btOn; private Button scanBT; static final int STATE_LISTENING=1; static final int STATE_CONNECTING=2; static final int STATE_CONNECTED=3; static final int STATE_CONNECTION_FAILED=4; static final int STATE_MESSAGE_RECEIVED=5; int REQUEST_ENABLE_BLUETOOTH=1; UUID MY_UUID = UUID.fromString("0F3BDD5C-0799-11E7-979A-C85B76F5CA58"); UUID myuuid; BroadcastReceiver mReceiver; BluetoothSocket bsock; BluetoothConnectActivityReceiver mBluetoothPickerReceiver = new BluetoothConnectActivityReceiver(); @RequiresApi(api = Build.VERSION_CODES.O) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Toast.makeText(MainActivity.this, "Successful Launch ", Toast.LENGTH_SHORT).show(); btOn = (Button) findViewById(R.id.BtOn); scanBT = (Button) findViewById(R.id.scanBT); mybtadapter = BluetoothAdapter.getDefaultAdapter(); // BLUETOOTH DEVICE PICKER BluetoothConnectActivityReceiver mBluetoothPickerReceiver = new BluetoothConnectActivityReceiver(); registerReceiver(mBluetoothPickerReceiver, new IntentFilter(BluetoothDevicePicker.ACTION_DEVICE_SELECTED)); scanBT.setOnClickListener(v -gt; { startActivity(new Intent(BluetoothDevicePicker.ACTION_LAUNCH) .putExtra(BluetoothDevicePicker.EXTRA_NEED_AUTH, false) .putExtra(BluetoothDevicePicker.EXTRA_FILTER_TYPE, BluetoothDevicePicker.FILTER_TYPE_ALL) .setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)); //Toast.makeText(getApplicationContext(), "scanning.", Toast.LENGTH_SHORT).show(); }); setupBT(); BTonOff(); } public class BluetoothConnectActivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(BluetoothDevicePicker.ACTION_DEVICE_SELECTED.equals(intent.getAction())) { context.unregisterReceiver(this); BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Toast.makeText(context, "device : " device.getName(), Toast.LENGTH_SHORT).show(); ClientClass clientClass=new ClientClass(device); clientClass.start(); } } } private void setupBT() { if (mybtadapter == null) { Toast.makeText(getApplicationContext(), "Bluetooth not supported", Toast.LENGTH_SHORT).show(); } if (mybtadapter.isEnabled()) { btOn.setText("Disable Bluetooth"); scanBT.setEnabled(true); } else { btOn.setText("Enable Bluetooth"); scanBT.setEnabled(false); } } private void BTonOff() { btOn.setOnClickListener(v -gt; { if (mybtadapter.isEnabled()) { mybtadapter.disable(); Toast.makeText(getApplicationContext(), "Bluetooth disabled.", Toast.LENGTH_SHORT).show(); btOn.setText("Enable Bluetooth"); scanBT.setEnabled(false); } else { mybtadapter.enable(); Toast.makeText(getApplicationContext(), "Bluetooth enabled.", Toast.LENGTH_SHORT).show(); btOn.setText("Disable Bluetooth"); scanBT.setEnabled(true); } }); } Handler handler= new Handler(new Handler.Callback() { @Override public boolean handleMessage(@NonNull Message msg) { switch (msg.what){ case STATE_LISTENING: Toast.makeText(getApplicationContext(), "Listening", Toast.LENGTH_SHORT).show(); break; case STATE_CONNECTING: Toast.makeText(getApplicationContext(), "CONNECTING", Toast.LENGTH_SHORT).show(); break; case STATE_CONNECTED: Toast.makeText(getApplicationContext(), "CONNECTED", Toast.LENGTH_SHORT).show(); break; case STATE_CONNECTION_FAILED: Toast.makeText(getApplicationContext(), "CONNECTION FAILED", Toast.LENGTH_SHORT).show(); break; case STATE_MESSAGE_RECEIVED: //Later break; } return false; } }); @Override public void onDestroy() { super.onDestroy(); if (mybtadapter.isDiscovering()){ mybtadapter.cancelDiscovery(); } unregisterReceiver(mReceiver); } private class ClientClass extends Thread { private BluetoothDevice device; private BluetoothSocket socket; public ClientClass (BluetoothDevice device1){ device=device1; try { socket= device.createInsecureRfcommSocketToServiceRecord(MY_UUID); Log.i("ben","Successfully created socket " socket.getRemoteDevice().getName()); } catch (IOException e) { Log.e("ben", "Could not create socket"); e.printStackTrace(); } } public void run(){ try { socket.connect(); Message message= Message.obtain(); message.what=STATE_CONNECTED; handler.sendMessage(message); } catch (IOException connectException) { Log.e("ben", "Could not connect",connectException); Message message= Message.obtain(); message.what=STATE_CONNECTION_FAILED; handler.sendMessage(message); // Unable to connect; close the socket and return. try { socket.close(); } catch (IOException closeException) { Log.e("ben", "Could not close the client socket", closeException); } return; } } } }
а вот и Логкот:
2021-11-09 13:32:49.857 22717-11546/com.example.jhonnysnewremote E/ben: Could not connect java.io.IOException: read failed, socket might closed or timeout, read ret: -1 at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:970) at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:984) at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:536) at com.example.jhonnysnewremote.MainActivity$ClientClass.run(MainActivity.java:168)