Advertisement
Guest User

Bluetooth

a guest
Jan 11th, 2017
332
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.41 KB | None | 0 0
  1. package adc.com.samplebluetooth;
  2.  
  3. import android.bluetooth.BluetoothAdapter;
  4. import android.bluetooth.BluetoothDevice;
  5. import android.bluetooth.BluetoothServerSocket;
  6. import android.bluetooth.BluetoothSocket;
  7. import android.content.BroadcastReceiver;
  8. import android.content.Context;
  9. import android.content.Intent;
  10. import android.content.IntentFilter;
  11. import android.os.ParcelUuid;
  12. import android.util.Log;
  13.  
  14. import java.io.DataOutputStream;
  15. import java.io.IOException;
  16. import java.lang.reflect.InvocationTargetException;
  17. import java.lang.reflect.Method;
  18. import java.util.ArrayList;
  19. import java.util.List;
  20. import java.util.Set;
  21. import java.util.UUID;
  22.  
  23. class Bluetooth {
  24.     private BluetoothAdapter mBluetoothAdapter;
  25.     private BluetoothServerSocket mmServerSocket;
  26.     private String TAG = "BluetoothLogs";
  27.     private BroadcastReceiver bluetoothReceiver;
  28.     private IntentFilter filter = new IntentFilter();
  29.     private Context context;
  30.     private String bluetoothName = "MyBluetooth";
  31.     private List<BluetoothDevice> devices = new ArrayList<>();
  32.     private Callback callback;
  33.     private DataOutputStream os;
  34.  
  35.     private BluetoothSocket mSocket;
  36.  
  37.  
  38.     Bluetooth(Context context) {
  39.         this.context = context;
  40.  
  41.         mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  42.         bluetoothReceiver = new BroadcastReceiver() {
  43.             @Override
  44.             public void onReceive(Context context, Intent intent) {
  45.                 final String action = intent.getAction();
  46.                 BluetoothDevice device;
  47.  
  48.                 switch (action) {
  49.                     case BluetoothAdapter.ACTION_STATE_CHANGED:
  50.                         final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
  51.                                 BluetoothAdapter.ERROR);
  52.                         switch (state) {
  53.                             case BluetoothAdapter.STATE_OFF:
  54.                                 Log.v(TAG, "Bluetooth off");
  55.                                 setMessage("Bluetooth off");
  56.                                 break;
  57.                             case BluetoothAdapter.STATE_TURNING_OFF:
  58.                                 Log.v(TAG, "Turning Bluetooth off...");
  59.                                 setMessage("Turning Bluetooth off...");
  60.                                 break;
  61.                             case BluetoothAdapter.STATE_ON:
  62.                                 Log.v(TAG, "Bluetooth on");
  63.                                 setMessage("Bluetooth on");
  64.                                 mBluetoothAdapter.setName(bluetoothName);
  65.                                 break;
  66.                             case BluetoothAdapter.STATE_TURNING_ON:
  67.                                 Log.v(TAG, "Turning Bluetooth on...");
  68.                                 setMessage("Turning Bluetooth on...");
  69.                                 break;
  70.                         }
  71.                         break;
  72.                     case BluetoothDevice.ACTION_FOUND:
  73.                         device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  74.                         Log.v(TAG, "Found: " + device.getName() + ":" + device.getAddress());
  75.                         setMessage("Found: " + device.getName() + ":" + device.getAddress());
  76.                         if (device.getName().contains(bluetoothName)) {
  77.                             if (devices.size() == 0) {
  78.                                 Log.v(TAG, "Added: " + device.getName() + ":" + device.getAddress() + " to device list.");
  79.                                 setMessage("Added: " + device.getName() + ":" + device.getAddress() + " to device list.");
  80.                                 devices.add(device);
  81.                                 pairDevice(device);
  82.                             } else {
  83.                                 for (BluetoothDevice bd : devices) {
  84.                                     if (!bd.getAddress().equals(device.getAddress())) {
  85.                                         Log.v(TAG, "Added: " + device.getName() + ":" + device.getAddress() + " to device list.");
  86.                                         setMessage("Added: " + device.getName() + ":" + device.getAddress() + " to device list.");
  87.                                         devices.add(device);
  88.                                         pairDevice(device);
  89.                                     }
  90.                                 }
  91.                             }
  92.                         }
  93.                         break;
  94.                     case BluetoothDevice.ACTION_ACL_CONNECTED:
  95.                         device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  96.                         Log.v(TAG, "Now paired to: " + device.getName() + ":" + device.getAddress());
  97.                         setMessage("Now paired to: " + device.getName() + ":" + device.getAddress());
  98.                         break;
  99.                     case BluetoothDevice.ACTION_PAIRING_REQUEST:
  100.                         try {
  101.                             device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  102.                             int pin = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_KEY, 0);
  103.  
  104.                             Log.v(TAG, device.getName());
  105.                             byte[] pinBytes = ("" + pin).getBytes("UTF-8");
  106.                             device.setPin(pinBytes);
  107.                             device.setPairingConfirmation(true);
  108.                         } catch (Exception e) {
  109.                             Log.e(TAG, "Error occurs when trying to auto pair");
  110.                             e.printStackTrace();
  111.                         }
  112.                         break;
  113.                     case BluetoothDevice.ACTION_BOND_STATE_CHANGED:
  114.                         device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  115.                         switch (device.getBondState()) {
  116.                             case BluetoothDevice.BOND_BONDED:
  117.                                 Log.v(TAG, "Bonded to " + device.getName());
  118.                                 if (callback != null) {
  119.                                     callback.bondComplete(device);
  120.                                 }
  121.                                 break;
  122.                             case BluetoothDevice.BOND_BONDING:
  123.                                 Log.v(TAG, "Bonding to" + device.getName());
  124.                                 break;
  125.                             case BluetoothDevice.BOND_NONE:
  126.                                 Log.v(TAG, "No Bond.");
  127.                                 break;
  128.                             default:
  129.                                 break;
  130.                         }
  131.                         break;
  132.                     default:
  133.                         break;
  134.                 }
  135.             }
  136.         };
  137.     }
  138.  
  139.     interface Callback {
  140.         void message(String message);
  141.  
  142.         void bondComplete(BluetoothDevice device);
  143.     }
  144.  
  145.     void setCallback(Callback callback) {
  146.         this.callback = callback;
  147.     }
  148.  
  149.     public void open() {
  150.         filter.addAction(BluetoothDevice.ACTION_FOUND);
  151.         filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
  152.         filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
  153.         filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
  154.         filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
  155.         filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
  156.         context.registerReceiver(bluetoothReceiver, filter);
  157.         if (mBluetoothAdapter == null) {
  158.             Log.v(TAG, "Bluetooth is not supported.");
  159.             setMessage("Bluetooth is not supported.");
  160.         } else {
  161.             if (!mBluetoothAdapter.isEnabled()) {
  162.                 Log.v(TAG, "Enabling Bluetooth...");
  163.                 setMessage("Enabling Bluetooth...");
  164.                 mBluetoothAdapter.enable();
  165.             } else {
  166.                 mBluetoothAdapter.setName(bluetoothName);
  167.                 Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
  168.                 for (BluetoothDevice bd : pairedDevices) {
  169.                     Log.v(TAG, "Device: " + bd.getName() + " : " + bd.getAddress());
  170.                     setMessage("Device: " + bd.getName() + " : " + bd.getAddress());
  171.                 }
  172.             }
  173.         }
  174.     }
  175.  
  176.     void close() {
  177.         if (context != null) {
  178.             context.unregisterReceiver(bluetoothReceiver);
  179.         } else {
  180.             Log.v(TAG, "Call init before calling any command.");
  181.         }
  182.     }
  183.  
  184.     void makeDiscoverable() {
  185.         Method method;
  186.         try {
  187.             method = mBluetoothAdapter.getClass().getMethod("setScanMode", int.class, int.class);
  188.             method.invoke(mBluetoothAdapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE, 0);
  189.             Log.v(TAG, "method invoke successfully");
  190.         } catch (Exception e) {
  191.             e.printStackTrace();
  192.         }
  193.     }
  194.  
  195.     void scan() {
  196.         mBluetoothAdapter.startDiscovery();
  197.     }
  198.  
  199.     //For Pairing
  200.     private void pairDevice(BluetoothDevice device) {
  201.         try {
  202.             Log.v(TAG, "Start Pairing...");
  203.             setMessage("Start Pairing...");
  204.             Method m = device.getClass().getMethod("createBond", (Class[]) null);
  205.             m.invoke(device, (Object[]) null);
  206.         } catch (Exception e) {
  207.             Log.e(TAG, e.getMessage());
  208.         }
  209.     }
  210.  
  211.     //For UnPairing
  212.     private void unpairDevice(BluetoothDevice device) {
  213.         try {
  214.             Log.v(TAG, "Start Un-Pairing...");
  215.             setMessage("Start Un-Pairing...");
  216.             Method m = device.getClass().getMethod("removeBond", (Class[]) null);
  217.             m.invoke(device, (Object[]) null);
  218.         } catch (Exception e) {
  219.             Log.e(TAG, e.getMessage());
  220.         }
  221.     }
  222.  
  223.     private void setMessage(String message) {
  224.         if (callback != null) {
  225.             callback.message(message);
  226.         }
  227.     }
  228.  
  229.     Set<BluetoothDevice> getPairedDevices() {
  230.         return mBluetoothAdapter.getBondedDevices();
  231.     }
  232.  
  233.     void connectToPaired(BluetoothDevice device){
  234.         if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
  235.             ParcelUuid[] uuid = device.getUuids();
  236.             Log.d(TAG, device.getName());
  237.             try {
  238.                 String deviceUUID = uuid[0].toString();
  239.                 Log.v(TAG, "Connecting to device: " + deviceUUID);
  240.                 mSocket = device.createRfcommSocketToServiceRecord(UUID.fromString(deviceUUID));
  241.                 if (mSocket != null) {
  242.                     mSocket.connect();
  243.                 }
  244.             } catch (Exception e) {
  245.                 e.printStackTrace();
  246.             } finally {
  247.                 if (mSocket != null) {
  248.                     try {
  249.                         mSocket.close();
  250.                     } catch (IOException e) {
  251.                         e.printStackTrace();
  252.                     }
  253.                 }
  254.             }
  255.         }
  256.     }
  257.  
  258.     void send(BluetoothDevice device) {
  259.         try{
  260.             Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
  261.             os = new DataOutputStream(mSocket.getOutputStream());
  262.             new ClientSock("Hello from " + mBluetoothAdapter.getAddress()).start();
  263.             Log.v(TAG, "Saying hello.");
  264.         } catch (Exception e) {
  265.             e.printStackTrace();
  266.         }
  267.     }
  268.  
  269.     private class ClientSock extends Thread {
  270.         String message;
  271.  
  272.         ClientSock(String message) {
  273.             this.message = message;
  274.         }
  275.  
  276.         public void run() {
  277.             try {
  278.                 os.writeBytes(message);
  279.                 os.flush();
  280.             } catch (Exception e1) {
  281.                 e1.printStackTrace();
  282.             }
  283.         }
  284.     }
  285.  
  286.     public String getUUID(){
  287.         Method getUuidsMethod;
  288.         String uuidString = "";
  289.         try {
  290.             getUuidsMethod =BluetoothAdapter.class.getDeclaredMethod("getUuids", null);
  291.  
  292.             ParcelUuid[] uuids = (ParcelUuid[]) getUuidsMethod.invoke(mBluetoothAdapter, null);
  293.             for (ParcelUuid uuid: uuids) {
  294.                 Log.d(TAG, "UUID: " + uuid.getUuid().toString());
  295.                 uuidString = uuid.getUuid().toString();
  296.             }
  297.         } catch (NoSuchMethodException e) {
  298.             e.printStackTrace();
  299.         } catch (InvocationTargetException e) {
  300.             e.printStackTrace();
  301.         } catch (IllegalAccessException e) {
  302.             e.printStackTrace();
  303.         }
  304.         return uuidString;
  305.     }
  306.  
  307. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement