package com.ConnectBluetoothAsynchronously; import com.google.appinventor.components.annotations.*; import com.google.appinventor.components.common.ComponentCategory; import com.google.appinventor.components.runtime.AndroidNonvisibleComponent; import com.google.appinventor.components.runtime.AndroidViewComponent; import com.google.appinventor.components.runtime.ComponentContainer; import com.google.appinventor.components.runtime.EventDispatcher; import com.google.appinventor.components.runtime.util.YailList; import com.google.appinventor.components.annotations.*; import com.google.appinventor.components.runtime.*; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.util.Log; import java.io.IOException; import java.util.UUID; @DesignerComponent(version = 1, // Extension Version description = "Extension for Bluetooth connection with asynchronous connection handling", category = ComponentCategory.EXTENSION, nonVisible = true, iconName = "images/bluetooth.png") @SimpleObject(external = true) public class BtAsynConnect extends AndroidNonvisibleComponent { private final String LOG_TAG = "BtAsynConnect"; private BluetoothAdapter bluetoothAdapter; private BluetoothSocket bluetoothSocket; private BluetoothClient vbluetoothClient; private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Standard UUID for Bluetooth SPP public BtAsynConnect(ComponentContainer container) { super(container.$form()); bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); } /** * Initiates an asynchronous Bluetooth connection. * * @param address The MAC address of the Bluetooth device. */ @SimpleFunction(description = "Connects to the Bluetooth device asynchronously.") public void ConnectBtAsynchronous(final String address,final BluetoothClient bluetoothClient) { this.vbluetoothClient = bluetoothClient; new Thread(new Runnable() { @Override public void run() { boolean status = false; status = bluetoothClient.Connect(address); // On successful connection, trigger the event AfterConnection(status); } }).start(); } /** * Event that triggers after a successful Bluetooth connection. */ @SimpleEvent(description = "Event triggered after a successful Bluetooth connection.") public void AfterConnection(boolean isConnected) { EventDispatcher.dispatchEvent(this, "AfterConnection",isConnected); } /** * Checks if the Bluetooth connection is established. * * @return true if connected, false otherwise. */ @SimpleFunction(description = "Checks if the Bluetooth connection is established.") public boolean IsConnected() { return bluetoothSocket != null && bluetoothSocket.isConnected(); } /** * Disconnect the Bluetooth connection. */ @SimpleFunction(description = "Disconnects the Bluetooth connection.") public void Disconnect() { vbluetoothClient.Disconnect(); } }