Friday 6 December 2013

 Bluetooth Connection in Android from Matt Bell's blog

Project Structure


Here is the java and xml code from Matt Bell's blog adapted to send data only:

[code]--------------------------------------------------------------------------------------

package here
imports here

public class BluetoothTest extends Activity
{
    TextView myLabel;
    EditText myTextbox;
    BluetoothAdapter mBluetoothAdapter;
    BluetoothSocket mmSocket;
    BluetoothDevice mmDevice;
   
    OutputStream mmOutputStream;
   

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
      
        setContentView(R.layout.activity_main); // need a activity_main layout XML file
// with these objects below in it (buttons, labels etc...):
      
        Button openButton = (Button) findViewById(R.id.open);
        Button sendButton = (Button) findViewById(R.id.send);
        Button closeButton = (Button) findViewById(R.id.close);
        myLabel = (TextView) findViewById(R.id.label);
        myTextbox = (EditText) findViewById(R.id.entry);

        // Open BT connection Button
        openButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                try
                {
                    findBT();
                    openBT();
                } catch (IOException ex)
                {
                }
            }
        });

        // Send Button
        sendButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                try
                {
                    sendData();
                } catch (IOException ex)
                {
                }
            }
        });

        // Close button
        closeButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                try
                {
                    closeBT();
                } catch (IOException ex)
                {
                }
            }
        });
    }

    void findBT()
    {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null)
        {
            myLabel.setText("No bluetooth adapter available");
        }

        if (!mBluetoothAdapter.isEnabled())
        {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0)
        {
            for (BluetoothDevice device : pairedDevices)
            {
                if (device.getName().equals("linvor"))// change accordingly
                {
                    mmDevice = device;
                    break;
                }
            }
        }
        myLabel.setText("Bluetooth Device Found");
    }

    void openBT() throws IOException
    {
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");                                                                                                                                                         

if (mmDevice != null) 
        {
            mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
            mmSocket.connect();
            mmOutputStream = mmSocket.getOutputStream();           

       
        myLabel.setText("Bluetooth Opened");
        }
    }

   

    void sendData() throws IOException
    {
        String msg = myTextbox.getText().toString();
        msg += "\n";
        mmOutputStream.write(msg.getBytes());
        myLabel.setText("Data Sent");
    }

    void closeBT() throws IOException
    {
      
        mmOutputStream.close();
        mmSocket.close();
        myLabel.setText("Bluetooth Closed");
    }
}// end of java code.


XML code: 
Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="your package"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:label="@string/app_name" >
        <activity android:name="BluetoothTest"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="5" android:targetSdkVersion="9"/>
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <supports-screens android:anyDensity="true" />
</manifest>



Layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:id="@+id/label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Type here:"/>
    <EditText
        android:id="@+id/entry"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@android:drawable/editbox_background"
        android:layout_below="@id/label"/>
    <Button
        android:id="@+id/open"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/entry"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="10dip"
        android:text="Open" />
    <Button
        android:id="@+id/send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/open"
        android:layout_alignTop="@id/open"
        android:text="Send" />
    <Button
        android:id="@+id/close"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/send"
        android:layout_alignTop="@id/send"
        android:text="Close" />
</RelativeLayout>


Arduino Test Code:
#include <SoftwareSerial.h>

int bluetoothTx = 2;
int bluetoothRx = 3;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
const int LED = 10;
char incomingByte = ' ';

void setup()
{
  //Setup usb serial connection to computer
  Serial.begin(9600);
  pinMode(LED, OUTPUT);
  //Setup Bluetooth serial connection to android
  bluetooth.begin(115200);
  bluetooth.print("$$$");
  delay(100);
  bluetooth.println("U,9600,N");
  bluetooth.begin(9600);
  Serial.println("Start");
 
}

void loop()
{


  //Read from bluetooth and write to usb serial
  if(bluetooth.available())
  {
    Serial.println("BlueTooth OK");
    char toSend = (char)bluetooth.read();
    Serial.println(toSend);
    incomingByte = toSend;
  }


if (incomingByte == 'l')
{
digitalWrite(LED, HIGH);
delay(500);
digitalWrite(LED, LOW);
}
 
}


[end code]----------------------------------------------