public class MainActivity extends AppCompatActivity {
public static final java.lang.String arduinoModuleName = "HC-05";
private int toastDuration = Toast.LENGTH_LONG;
public BluetoothDevice queryDevices(java.lang.String deviceToFind, BluetoothAdapter btAdapter){
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
boolean isAMatchingDevice = false;
BluetoothDevice matchingDevice = null;
Context context = getApplicationContext(); //for Toast
Toast toast = Toast.makeText(context,"Found Arduino Module in Paired Devices", toastDuration);
if (pairedDevices.size() > 0) {
// There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
if (deviceName.equals(deviceToFind)) {
isAMatchingDevice = true;
matchingDevice = device;
}
}
}
if(!isAMatchingDevice){
toast = Toast.makeText(context, "No paired devices found", toastDuration);
toast.show();
}
return matchingDevice;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice arduinoModule;
final byte[] testBytes = {6};
if (!mBluetoothAdapter.isEnabled()) { //if bluetooth isn't enabled, enable it
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
arduinoModule = queryDevices(arduinoModuleName, mBluetoothAdapter); //set arduinoModule device to device with name "HC-05"
ParcelUuid [] uuid = arduinoModule.getUuids();
Log.d("Eren-onCreate", "Found arduino module: " + arduinoModule + "\n");
Log.d("Eren-onCreate", "Device name: " + arduinoModule.getName());
// Log.d("Eren-onCreate", "UUID of remote device: " + uuid[0].getUuid());
Log.d("Eren-onCreate", "UUIDs: " + uuid);
Log.d("Eren-onCreate", "Bluetooth Class: " + arduinoModule.getBluetoothClass());
Log.d("Eren-onCreate", "Device bond state: " + arduinoModule.getBondState());
Log.d("Eren-onCreate", "");
Log.d("Eren-onCreate", "Creating new socket to connect");
final ConnectThread newThread = new ConnectThread(arduinoModule);
Log.d("Eren-onCreate", "Connecting Socket");
newThread.run();
final ConnectedThread btThread = newThread.getConnection();
Context context = getApplicationContext(); //for Toast
Toast toast = Toast.makeText(context,"Connected to Bluetooth Module...", toastDuration);
toast.show();
//Button control to manipulate thread connection
final Button btn = (Button)findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btThread.write(testBytes);
}
});
}
}