Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package adc.com.samplebluetooth;
- import android.bluetooth.BluetoothAdapter;
- import android.bluetooth.BluetoothDevice;
- import android.bluetooth.BluetoothServerSocket;
- import android.bluetooth.BluetoothSocket;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.os.ParcelUuid;
- import android.util.Log;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Set;
- import java.util.UUID;
- class Bluetooth {
- private BluetoothAdapter mBluetoothAdapter;
- private BluetoothServerSocket mmServerSocket;
- private String TAG = "BluetoothLogs";
- private BroadcastReceiver bluetoothReceiver;
- private IntentFilter filter = new IntentFilter();
- private Context context;
- private String bluetoothName = "MyBluetooth";
- private List<BluetoothDevice> devices = new ArrayList<>();
- private Callback callback;
- private DataOutputStream os;
- private BluetoothSocket mSocket;
- Bluetooth(Context context) {
- this.context = context;
- mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
- bluetoothReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- final String action = intent.getAction();
- BluetoothDevice device;
- switch (action) {
- case BluetoothAdapter.ACTION_STATE_CHANGED:
- final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
- BluetoothAdapter.ERROR);
- switch (state) {
- case BluetoothAdapter.STATE_OFF:
- Log.v(TAG, "Bluetooth off");
- setMessage("Bluetooth off");
- break;
- case BluetoothAdapter.STATE_TURNING_OFF:
- Log.v(TAG, "Turning Bluetooth off...");
- setMessage("Turning Bluetooth off...");
- break;
- case BluetoothAdapter.STATE_ON:
- Log.v(TAG, "Bluetooth on");
- setMessage("Bluetooth on");
- mBluetoothAdapter.setName(bluetoothName);
- break;
- case BluetoothAdapter.STATE_TURNING_ON:
- Log.v(TAG, "Turning Bluetooth on...");
- setMessage("Turning Bluetooth on...");
- break;
- }
- break;
- case BluetoothDevice.ACTION_FOUND:
- device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- Log.v(TAG, "Found: " + device.getName() + ":" + device.getAddress());
- setMessage("Found: " + device.getName() + ":" + device.getAddress());
- if (device.getName().contains(bluetoothName)) {
- if (devices.size() == 0) {
- Log.v(TAG, "Added: " + device.getName() + ":" + device.getAddress() + " to device list.");
- setMessage("Added: " + device.getName() + ":" + device.getAddress() + " to device list.");
- devices.add(device);
- pairDevice(device);
- } else {
- for (BluetoothDevice bd : devices) {
- if (!bd.getAddress().equals(device.getAddress())) {
- Log.v(TAG, "Added: " + device.getName() + ":" + device.getAddress() + " to device list.");
- setMessage("Added: " + device.getName() + ":" + device.getAddress() + " to device list.");
- devices.add(device);
- pairDevice(device);
- }
- }
- }
- }
- break;
- case BluetoothDevice.ACTION_ACL_CONNECTED:
- device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- Log.v(TAG, "Now paired to: " + device.getName() + ":" + device.getAddress());
- setMessage("Now paired to: " + device.getName() + ":" + device.getAddress());
- break;
- case BluetoothDevice.ACTION_PAIRING_REQUEST:
- try {
- device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- int pin = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_KEY, 0);
- Log.v(TAG, device.getName());
- byte[] pinBytes = ("" + pin).getBytes("UTF-8");
- device.setPin(pinBytes);
- device.setPairingConfirmation(true);
- } catch (Exception e) {
- Log.e(TAG, "Error occurs when trying to auto pair");
- e.printStackTrace();
- }
- break;
- case BluetoothDevice.ACTION_BOND_STATE_CHANGED:
- device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- switch (device.getBondState()) {
- case BluetoothDevice.BOND_BONDED:
- Log.v(TAG, "Bonded to " + device.getName());
- if (callback != null) {
- callback.bondComplete(device);
- }
- break;
- case BluetoothDevice.BOND_BONDING:
- Log.v(TAG, "Bonding to" + device.getName());
- break;
- case BluetoothDevice.BOND_NONE:
- Log.v(TAG, "No Bond.");
- break;
- default:
- break;
- }
- break;
- default:
- break;
- }
- }
- };
- }
- interface Callback {
- void message(String message);
- void bondComplete(BluetoothDevice device);
- }
- void setCallback(Callback callback) {
- this.callback = callback;
- }
- public void open() {
- filter.addAction(BluetoothDevice.ACTION_FOUND);
- filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
- filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
- filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
- filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
- filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
- context.registerReceiver(bluetoothReceiver, filter);
- if (mBluetoothAdapter == null) {
- Log.v(TAG, "Bluetooth is not supported.");
- setMessage("Bluetooth is not supported.");
- } else {
- if (!mBluetoothAdapter.isEnabled()) {
- Log.v(TAG, "Enabling Bluetooth...");
- setMessage("Enabling Bluetooth...");
- mBluetoothAdapter.enable();
- } else {
- mBluetoothAdapter.setName(bluetoothName);
- Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
- for (BluetoothDevice bd : pairedDevices) {
- Log.v(TAG, "Device: " + bd.getName() + " : " + bd.getAddress());
- setMessage("Device: " + bd.getName() + " : " + bd.getAddress());
- }
- }
- }
- }
- void close() {
- if (context != null) {
- context.unregisterReceiver(bluetoothReceiver);
- } else {
- Log.v(TAG, "Call init before calling any command.");
- }
- }
- void makeDiscoverable() {
- Method method;
- try {
- method = mBluetoothAdapter.getClass().getMethod("setScanMode", int.class, int.class);
- method.invoke(mBluetoothAdapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE, 0);
- Log.v(TAG, "method invoke successfully");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- void scan() {
- mBluetoothAdapter.startDiscovery();
- }
- //For Pairing
- private void pairDevice(BluetoothDevice device) {
- try {
- Log.v(TAG, "Start Pairing...");
- setMessage("Start Pairing...");
- Method m = device.getClass().getMethod("createBond", (Class[]) null);
- m.invoke(device, (Object[]) null);
- } catch (Exception e) {
- Log.e(TAG, e.getMessage());
- }
- }
- //For UnPairing
- private void unpairDevice(BluetoothDevice device) {
- try {
- Log.v(TAG, "Start Un-Pairing...");
- setMessage("Start Un-Pairing...");
- Method m = device.getClass().getMethod("removeBond", (Class[]) null);
- m.invoke(device, (Object[]) null);
- } catch (Exception e) {
- Log.e(TAG, e.getMessage());
- }
- }
- private void setMessage(String message) {
- if (callback != null) {
- callback.message(message);
- }
- }
- Set<BluetoothDevice> getPairedDevices() {
- return mBluetoothAdapter.getBondedDevices();
- }
- void connectToPaired(BluetoothDevice device){
- if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
- ParcelUuid[] uuid = device.getUuids();
- Log.d(TAG, device.getName());
- try {
- String deviceUUID = uuid[0].toString();
- Log.v(TAG, "Connecting to device: " + deviceUUID);
- mSocket = device.createRfcommSocketToServiceRecord(UUID.fromString(deviceUUID));
- if (mSocket != null) {
- mSocket.connect();
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (mSocket != null) {
- try {
- mSocket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
- void send(BluetoothDevice device) {
- try{
- Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
- os = new DataOutputStream(mSocket.getOutputStream());
- new ClientSock("Hello from " + mBluetoothAdapter.getAddress()).start();
- Log.v(TAG, "Saying hello.");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private class ClientSock extends Thread {
- String message;
- ClientSock(String message) {
- this.message = message;
- }
- public void run() {
- try {
- os.writeBytes(message);
- os.flush();
- } catch (Exception e1) {
- e1.printStackTrace();
- }
- }
- }
- public String getUUID(){
- Method getUuidsMethod;
- String uuidString = "";
- try {
- getUuidsMethod =BluetoothAdapter.class.getDeclaredMethod("getUuids", null);
- ParcelUuid[] uuids = (ParcelUuid[]) getUuidsMethod.invoke(mBluetoothAdapter, null);
- for (ParcelUuid uuid: uuids) {
- Log.d(TAG, "UUID: " + uuid.getUuid().toString());
- uuidString = uuid.getUuid().toString();
- }
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- return uuidString;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement