Advertisement
iderrington

Bluetooth Connection Manager

May 25th, 2013
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.64 KB | None | 0 0
  1. /*
  2.  * This class takes a Bluetooth device and manages the connection state
  3.  * Largely taken from the Android website.
  4.  *
  5.  * Author: Iain Derrington (@IDerrington)
  6.  * http://kandi-electronics.co.uk
  7.  * http://soldercore.com (@SolderCore)
  8.  *
  9.  * License: Car & Motorbike both clean.
  10.  *
  11.  * Version: LOL
  12.  *
  13.  */
  14. package com.kandi.soldercorebt2;
  15.  
  16. import java.io.IOException;
  17. import java.io.InputStream;
  18. import java.io.OutputStream;
  19. import java.util.UUID;
  20.  
  21. import android.bluetooth.BluetoothAdapter;
  22. import android.bluetooth.BluetoothDevice;
  23. import android.bluetooth.BluetoothSocket;
  24. import android.os.Handler;
  25. import android.util.Log;
  26.  
  27.  
  28. public class BTConnection extends Thread{
  29.     public static final String TAG = BTConnection.class.getName();
  30.     private  final UUID MY_UUID_SECURE =
  31.             UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  32.     private  Handler mHandler; 
  33.     private  BluetoothSocket mmSocket;
  34.     private  BluetoothDevice mmDevice;
  35.     private  BluetoothAdapter btAdapter;
  36.     private  ConnectedThread btThread;
  37.  
  38.     /*
  39.      *
  40.      */
  41.     public BTConnection(BluetoothAdapter btAdapter,BluetoothDevice btDevice, Handler mHander){
  42.         BluetoothSocket tmp = null;
  43.        
  44.         this.mHandler = mHander;
  45.         this.mmDevice = btDevice;
  46.         this.btAdapter = btAdapter;
  47.        
  48.         // Get a BluetoothSocket to connect with the given BluetoothDevice
  49.         try {
  50.             // MY_UUID is the app's UUID string, also used by the server code
  51.             tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
  52.         } catch (IOException e) { }
  53.         mmSocket = tmp;
  54.     }
  55.     /*
  56.      *
  57.      */
  58.     public void write(String text){
  59.         text = String.format(text+"%n");
  60.         btThread.write(text.getBytes());
  61.     }
  62.    
  63.     /*
  64.      * (non-Javadoc)
  65.      * @see java.lang.Thread#run()
  66.      */
  67.      public void run() {
  68.             // Cancel discovery because it will slow down the connection
  69.             btAdapter.cancelDiscovery();
  70.      
  71.             try {
  72.                 // Connect the device through the socket. This will block
  73.                 // until it succeeds or throws an exception
  74.                 mmSocket.connect();
  75.             } catch (IOException connectException) {
  76.                 Log.e(TAG, "Unable to connect to " + mmDevice.getName());
  77.                 // Unable to connect; close the socket and get out
  78.                 try {
  79.                     mmSocket.close();
  80.                     return;
  81.                 } catch (IOException closeException) {
  82.                     Log.e(TAG, "Unable to close failed connection");
  83.                     return;
  84.                 }
  85.             }
  86.             // Do work to manage the connection (in a separate thread)
  87.             btThread = new ConnectedThread(mmSocket);
  88.             btThread.start();
  89.            
  90.             return;
  91.         }
  92.      
  93.      public void cancel(){
  94.          if (btThread != null){
  95.              btThread.cancel();
  96.          }
  97.      }
  98.      
  99.      
  100.      private class ConnectedThread extends Thread {
  101.             private static final int MESSAGE_READ = 0;
  102.             private final BluetoothSocket mmSocket;
  103.             private final InputStream mmInStream;
  104.             private final OutputStream mmOutStream;
  105.          
  106.             public ConnectedThread(BluetoothSocket socket) {
  107.                 mmSocket = socket;
  108.                 InputStream tmpIn = null;
  109.                 OutputStream tmpOut = null;
  110.          
  111.                 // Get the input and output streams, using temp objects because
  112.                 // member streams are final
  113.                 try {
  114.                     tmpIn = socket.getInputStream();
  115.                     tmpOut = socket.getOutputStream();
  116.                 } catch (IOException e) { }
  117.          
  118.                 mmInStream = tmpIn;
  119.                 mmOutStream = tmpOut;
  120.             }
  121.          
  122.             public void run() {
  123.                 byte[] buffer = new byte[1024];  // buffer store for the stream
  124.                 int bytes; // bytes returned from read()
  125.          
  126.                 // Keep listening to the InputStream until an exception occurs
  127.                 while (true) {
  128.                     try {
  129.                         // Read from the InputStream
  130.                         bytes = mmInStream.read(buffer);
  131.                         // Send the obtained bytes to the UI activity
  132.                         mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
  133.                                 .sendToTarget();
  134.                     } catch (IOException e) {
  135.                         break;
  136.                     }
  137.                 }
  138.             }
  139.          
  140.             /* Call this from the main activity to send data to the remote device */
  141.             public void write(byte[] bytes) {
  142.                 try {
  143.                     mmOutStream.write(bytes);
  144.                 } catch (IOException e) { }
  145.             }
  146.          
  147.             /* Call this from the main activity to shutdown the connection */
  148.             public void cancel() {
  149.                 try {
  150.                     mmSocket.close();
  151.                 } catch (IOException e) { }
  152.             }
  153.         }
  154. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement