Bluetooth Communication Betwixt Android Devices

Posted on

This practise implement bi-direction Bluetooth communication betwixt Android devices. After connectedness made inwards in conclusion postal service “Make BlueTooth connectedness betwixt Android devices“, initiatory of all unopen to other thread, ThreadConnected, to grip read as well as write once BluetoothSocket established. If whatsoever illustration brand the connectedness lost, the programme volition non re-connect, then you lot lead maintain to quit as well as re-start it.


delight notice that it is only a practise to written report bluetooth, non a completed example.


AndroidBlueToothBeCOnnected:

MainActivity.java

package com.example.androidbluetoothbeconnected;  import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID;  import android.support.v7.app.ActionBarActivity; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast;  populace aeroplane MainActivity extends ActionBarActivity {    soul static in conclusion int REQUEST_ENABLE_BT = 1;    BluetoothAdapter bluetoothAdapter;    soul UUID myUUID;  soul String myName;    LinearLayout inputPane;  EditText inputField;  Button btnSend;   TextView textInfo, textStatus;    ThreadBeConnected myThreadBeConnected;  ThreadConnected myThreadConnected;    @Override  protected void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentView(R.layout.activity_main);   textInfo = (TextView)findViewById(R.id.info);   textStatus = (TextView)findViewById(R.id.status);      inputPane = (LinearLayout)findViewById(R.id.inputpane);   inputField = (EditText)findViewById(R.id.input);   btnSend = (Button)findViewById(R.id.send);   btnSend.setOnClickListener(new OnClickListener(){     @Override    populace void onClick(View v) {     if(myThreadConnected!=null){      byte[] bytesToSend = inputField.getText().toString().getBytes();      myThreadConnected.write(bytesToSend);     }    }});      if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)){    Toast.makeText(this,      "FEATURE_BLUETOOTH NOT support",      Toast.LENGTH_LONG).show();             finish();             return;   }    //generate UUID on web: http://www.famkruithof.net/uuid/uuidgen   //have to stand upwards for the UUID on the unopen to other device of the BT connectedness   myUUID = UUID.fromString("ec79da00-853f-11e4-b4a9-0800200c9a66");   myName = myUUID.toString();      bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();   if (bluetoothAdapter == null) {    Toast.makeText(this,      "Bluetooth is non supported on this hardware platform",      Toast.LENGTH_LONG).show();             finish();             return;   }      String stInfo = bluetoothAdapter.getName() + "\n" +       bluetoothAdapter.getAddress();   textInfo.setText(stInfo);  }    @Override  protected void onStart() {   super.onStart();      //Turn ON BlueTooth if it is OFF   if (!bluetoothAdapter.isEnabled()) {             Intent enableIntent = novel Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);             startActivityForResult(enableIntent, REQUEST_ENABLE_BT);         }      setup();  }    soul void setup() {   textStatus.setText("setup()");   myThreadBeConnected = novel ThreadBeConnected();   myThreadBeConnected.start();  }    @Override  protected void onDestroy() {   super.onDestroy();      if(myThreadBeConnected!=null){    myThreadBeConnected.cancel();   }  }   @Override  protected void onActivityResult(int requestCode, int resultCode, Intent data) {      if(requestCode==REQUEST_ENABLE_BT){    if(resultCode == Activity.RESULT_OK){     setup();    }else{     Toast.makeText(this,       "BlueTooth NOT enabled",       Toast.LENGTH_SHORT).show();              finish();    }   }   }    soul aeroplane ThreadBeConnected extends Thread {      soul BluetoothServerSocket bluetoothServerSocket = null;      populace ThreadBeConnected() {    essay {     bluetoothServerSocket =        bluetoothAdapter.listenUsingRfcommWithServiceRecord(myName, myUUID);          textStatus.setText("Waiting\n"       + "bluetoothServerSocket :\n"      + bluetoothServerSocket);    } grab (IOException e) {     // TODO Auto-generated grab block     e.printStackTrace();    }   }    @Override   populace void run() {    BluetoothSocket bluetoothSocket = null;        if(bluetoothServerSocket!=null){     essay {      bluetoothSocket = bluetoothServerSocket.accept();            BluetoothDevice remoteDevice = bluetoothSocket.getRemoteDevice();            in conclusion String strConnected = "Connected:\n" +        remoteDevice.getName() + "\n" +        remoteDevice.getAddress();            //connected      runOnUiThread(new Runnable(){        @Override       populace void run() {        textStatus.setText(strConnected);        inputPane.setVisibility(View.VISIBLE);       }});            startThreadConnected(bluetoothSocket);           } grab (IOException e) {      // TODO Auto-generated grab block      e.printStackTrace();            in conclusion String eMessage = e.getMessage();      runOnUiThread(new Runnable(){        @Override       populace void run() {        textStatus.setText("something wrong: \n" + eMessage);       }});     }    }else{     runOnUiThread(new Runnable(){       @Override      populace void run() {       textStatus.setText("bluetoothServerSocket == null");      }});    }   }      populace void cancel() {        Toast.makeText(getApplicationContext(),      "close bluetoothServerSocket",      Toast.LENGTH_LONG).show();        essay {     bluetoothServerSocket.close();    } grab (IOException e) {     // TODO Auto-generated grab block     e.printStackTrace();    }         }  }   soul void startThreadConnected(BluetoothSocket socket){      myThreadConnected = novel ThreadConnected(socket);   myThreadConnected.start();  }    soul aeroplane ThreadConnected extends Thread {   soul in conclusion BluetoothSocket connectedBluetoothSocket;         soul in conclusion InputStream connectedInputStream;         soul in conclusion OutputStream connectedOutputStream;      populace ThreadConnected(BluetoothSocket socket) {    connectedBluetoothSocket = socket;    InputStream inwards = null;             OutputStream out = null;                          essay {     inwards = socket.getInputStream();     out = socket.getOutputStream();    } grab (IOException e) {     // TODO Auto-generated grab block     e.printStackTrace();    }                          connectedInputStream = in;             connectedOutputStream = out;   }    @Override   populace void run() {    byte[] buffer = novel byte[1024];             int bytes;                          acre (true) {              essay {      bytes = connectedInputStream.read(buffer);            String strReceived = novel String(buffer, 0, bytes);      in conclusion String msgReceived = String.valueOf(bytes) +         " bytes received:\n"         + strReceived;       runOnUiThread(new Runnable(){        @Override       populace void run() {        textStatus.setText(msgReceived);       }});           } grab (IOException e) {      // TODO Auto-generated grab block      e.printStackTrace();            in conclusion String msgConnectionLost = "Connection lost:\n"        + e.getMessage();      runOnUiThread(new Runnable(){        @Override       populace void run() {        textStatus.setText(msgConnectionLost);       }});     }             }   }      populace void write(byte[] buffer) {    essay {     connectedOutputStream.write(buffer);     connectedOutputStream.flush();    } grab (IOException e) {     // TODO Auto-generated grab block     e.printStackTrace();    }         }      populace void cancel() {    essay {     connectedBluetoothSocket.close();    } grab (IOException e) {     // TODO Auto-generated grab block     e.printStackTrace();    }   }   } } 

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     android:orientation="vertical"     tools:context="com.example.androidbluetoothbeconnected.MainActivity" >      <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_gravity="center_horizontal"         android:autoLink="web"         android:text="https://rootandroid.org//"         android:textStyle="bold" />          <TextView         android:id="@+id/info"         android:textStyle="bold|italic"         android:layout_width="wrap_content"         android:layout_height="wrap_content"/>     <TextView         android:id="@+id/status"         android:textSize="28sp"         android:layout_width="wrap_content"         android:layout_height="wrap_content"/>          <LinearLayout         android:id="@+id/inputpane"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:orientation="vertical"         android:visibility="gone">                  <EditText             android:id="@+id/input"             android:layout_width="match_parent"             android:layout_height="wrap_content"/>         <Button             android:id="@+id/send"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:text="Sent"/>              </LinearLayout>  </LinearLayout> 

direction Bluetooth communication betwixt Android devices Bluetooth communication betwixt Android devicesDownload the files.


AndroidBlueTooth:

MainActivity.java

package com.example.androidbluetooth;  import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Set; import java.util.UUID;  import android.support.v7.app.ActionBarActivity; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast;  populace aeroplane MainActivity extends ActionBarActivity {    soul static in conclusion int REQUEST_ENABLE_BT = 1;    BluetoothAdapter bluetoothAdapter;    ArrayList<BluetoothDevice> pairedDeviceArrayList;    TextView textInfo, textStatus;  ListView listViewPairedDevice;  ArrayAdapter<BluetoothDevice> pairedDeviceAdapter;  soul UUID myUUID;    LinearLayout inputPane;  EditText inputField;  Button btnSend;    ThreadConnectBTdevice myThreadConnectBTdevice;  ThreadConnected myThreadConnected;   @Override  protected void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentView(R.layout.activity_main);   textInfo = (TextView)findViewById(R.id.info);   textStatus = (TextView)findViewById(R.id.status);   listViewPairedDevice = (ListView)findViewById(R.id.pairedlist);      inputPane = (LinearLayout)findViewById(R.id.inputpane);   inputField = (EditText)findViewById(R.id.input);   btnSend = (Button)findViewById(R.id.send);   btnSend.setOnClickListener(new OnClickListener(){     @Override    populace void onClick(View v) {     if(myThreadConnected!=null){      byte[] bytesToSend = inputField.getText().toString().getBytes();      myThreadConnected.write(bytesToSend);     }    }});      if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)){    Toast.makeText(this,      "FEATURE_BLUETOOTH NOT support",      Toast.LENGTH_LONG).show();             finish();             return;   }    //generate UUID on web: http://www.famkruithof.net/uuid/uuidgen   //have to stand upwards for the UUID on the unopen to other device of the BT connectedness   myUUID = UUID.fromString("ec79da00-853f-11e4-b4a9-0800200c9a66");      bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();   if (bluetoothAdapter == null) {    Toast.makeText(this,      "Bluetooth is non supported on this hardware platform",      Toast.LENGTH_LONG).show();             finish();             return;   }      String stInfo = bluetoothAdapter.getName() + "\n" +     bluetoothAdapter.getAddress();   textInfo.setText(stInfo);  }   @Override  protected void onStart() {   super.onStart();      //Turn ON BlueTooth if it is OFF   if (!bluetoothAdapter.isEnabled()) {             Intent enableIntent = novel Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);             startActivityForResult(enableIntent, REQUEST_ENABLE_BT);         }      setup();  }    soul void setup() {   Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();   if (pairedDevices.size() > 0) {    pairedDeviceArrayList = novel ArrayList<BluetoothDevice>();        for (BluetoothDevice device : pairedDevices) {     pairedDeviceArrayList.add(device);             }        pairedDeviceAdapter = novel ArrayAdapter<BluetoothDevice>(this,                  android.R.layout.simple_list_item_1, pairedDeviceArrayList);    listViewPairedDevice.setAdapter(pairedDeviceAdapter);        listViewPairedDevice.setOnItemClickListener(new OnItemClickListener(){      @Override     populace void onItemClick(AdapterView<?> parent, View view,       int position, long id) {      BluetoothDevice device =         (BluetoothDevice)parent.getItemAtPosition(position);       Toast.makeText(MainActivity.this,         "Name: " + device.getName() + "\n"        + "Address: " + device.getAddress() + "\n"        + "BondState: " + device.getBondState() + "\n"        + "BluetoothClass: " + device.getBluetoothClass() + "\n"        + "Class: " + device.getClass(),        Toast.LENGTH_LONG).show();              textStatus.setText("start ThreadConnectBTdevice");       myThreadConnectBTdevice = novel ThreadConnectBTdevice(device);       myThreadConnectBTdevice.start();     }});   }  }   @Override  protected void onDestroy() {   super.onDestroy();      if(myThreadConnectBTdevice!=null){    myThreadConnectBTdevice.cancel();   }  }   @Override  protected void onActivityResult(int requestCode, int resultCode, Intent data) {      if(requestCode==REQUEST_ENABLE_BT){    if(resultCode == Activity.RESULT_OK){     setup();    }else{     Toast.makeText(this,       "BlueTooth NOT enabled",       Toast.LENGTH_SHORT).show();              finish();    }   }   }    soul aeroplane ThreadConnectBTdevice extends Thread {   soul BluetoothSocket bluetoothSocket = null;         soul in conclusion BluetoothDevice bluetoothDevice;                           populace ThreadConnectBTdevice(BluetoothDevice device) {          bluetoothDevice = device;           essay {     bluetoothSocket = device.createRfcommSocketToServiceRecord(myUUID);     textStatus.setText("bluetoothSocket: \n" + bluetoothSocket);    } grab (IOException e) {     // TODO Auto-generated grab block     e.printStackTrace();    }         }    @Override   populace void run() {    boolean success = false;    essay {     bluetoothSocket.connect();     success = true;    } grab (IOException e) {     e.printStackTrace();          in conclusion String eMessage = e.getMessage();     runOnUiThread(new Runnable(){       @Override      populace void run() {       textStatus.setText("something incorrect bluetoothSocket.connect(): \n" + eMessage);      }});          essay {      bluetoothSocket.close();     } grab (IOException e1) {      // TODO Auto-generated grab block      e1.printStackTrace();     }    }        if(success){     //connect successful     in conclusion String msgconnected = "connect successful:\n"      + "BluetoothSocket: " + bluetoothSocket + "\n"      + "BluetoothDevice: " + bluetoothDevice;          runOnUiThread(new Runnable(){       @Override      populace void run() {       textStatus.setText(msgconnected);              listViewPairedDevice.setVisibility(View.GONE);       inputPane.setVisibility(View.VISIBLE);      }});          startThreadConnected(bluetoothSocket);    }else{     //fail    }   }      populace void cancel() {        Toast.makeText(getApplicationContext(),       "close bluetoothSocket",       Toast.LENGTH_LONG).show();        essay {     bluetoothSocket.close();    } grab (IOException e) {     // TODO Auto-generated grab block     e.printStackTrace();    }             }  }    soul void startThreadConnected(BluetoothSocket socket){      myThreadConnected = novel ThreadConnected(socket);   myThreadConnected.start();  }    soul aeroplane ThreadConnected extends Thread {   soul in conclusion BluetoothSocket connectedBluetoothSocket;         soul in conclusion InputStream connectedInputStream;         soul in conclusion OutputStream connectedOutputStream;      populace ThreadConnected(BluetoothSocket socket) {    connectedBluetoothSocket = socket;    InputStream inwards = null;             OutputStream out = null;                          essay {     inwards = socket.getInputStream();     out = socket.getOutputStream();    } grab (IOException e) {     // TODO Auto-generated grab block     e.printStackTrace();    }                          connectedInputStream = in;             connectedOutputStream = out;   }    @Override   populace void run() {    byte[] buffer = novel byte[1024];             int bytes;                          acre (true) {              essay {      bytes = connectedInputStream.read(buffer);      String strReceived = novel String(buffer, 0, bytes);      in conclusion String msgReceived = String.valueOf(bytes) +         " bytes received:\n"         + strReceived;            runOnUiThread(new Runnable(){        @Override       populace void run() {        textStatus.setText(msgReceived);       }});           } grab (IOException e) {      // TODO Auto-generated grab block      e.printStackTrace();            in conclusion String msgConnectionLost = "Connection lost:\n"        + e.getMessage();      runOnUiThread(new Runnable(){        @Override       populace void run() {        textStatus.setText(msgConnectionLost);       }});     }             }   }      populace void write(byte[] buffer) {    essay {     connectedOutputStream.write(buffer);    } grab (IOException e) {     // TODO Auto-generated grab block     e.printStackTrace();    }         }      populace void cancel() {    essay {     connectedBluetoothSocket.close();    } grab (IOException e) {     // TODO Auto-generated grab block     e.printStackTrace();    }   }   }   } 

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     android:orientation="vertical"     tools:context="com.example.androidbluetooth.MainActivity" >      <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_gravity="center_horizontal"         android:autoLink="web"         android:text="https://rootandroid.org//"         android:textStyle="bold" />          <TextView         android:id="@+id/info"         android:textStyle="bold|italic"         android:layout_width="wrap_content"         android:layout_height="wrap_content"/>     <TextView         android:id="@+id/status"         android:textSize="28sp"         android:layout_width="wrap_content"         android:layout_height="wrap_content"/>          <ListView          android:id="@+id/pairedlist"         android:layout_width="match_parent"         android:layout_height="match_parent"/>          <LinearLayout         android:id="@+id/inputpane"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:orientation="vertical"         android:visibility="gone">                  <EditText             android:id="@+id/input"             android:layout_width="match_parent"             android:layout_height="wrap_content"/>         <Button             android:id="@+id/send"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:text="Sent"/>              </LinearLayout>  </LinearLayout> 

direction Bluetooth communication betwixt Android devices Bluetooth communication betwixt Android devicesDownload the files.


Remark: both side lead maintain to alter AndroidManifest.xml to add together permission of “android.permission.BLUETOOTH”.


Related:
Android illustration to communicate amongst Bluetooth device, HC-06 Bluetooth Module