Example usage for android.bluetooth BluetoothDevice getAddress

List of usage examples for android.bluetooth BluetoothDevice getAddress

Introduction

In this page you can find the example usage for android.bluetooth BluetoothDevice getAddress.

Prototype

public String getAddress() 

Source Link

Document

Returns the hardware address of this BluetoothDevice.

Usage

From source file:com.example.nachiketvatkar.locateus.BluetoothPairing.java

private void connect(BluetoothDevice device) {
    boolean isConnecting = mBleManager.connect(this, device.getAddress());
    if (isConnecting) {
        showConnectionStatus(true);/* ww w . j av  a 2 s  .  com*/
        System.out.println("CONNECTED TO THE DEVICE");
    }
}

From source file:com.cs4644.vt.theonering.MainActivity.java

private void connect(BluetoothDevice device) {
    boolean isConnecting = mBleManager.connect(this, device.getAddress());

    if (isConnecting) {
        showConnectionStatus(true);/* ww w  . j  a  v  a2 s .  com*/
    }
}

From source file:com.android.dragonkeyboardfirmwareupdater.KeyboardFirmwareUpdateService.java

/**
 * Handles intents ACTION_CONNECTION_STATE_CHANGED, ACTION_STATE_CHANGED,
 * ACTION_BOND_STATE_CHANGED, ACTION_KEYBOARD_UPDATE_CONFIRMED.
 * <p/>//from  w  w w. j a va 2s .  com
 * [ACTION_STATE_CHANGED]
 * This action is used to keep track of ON/OFF state change on the system Bluetooth adapter.
 * The
 * purpose is to synchronize the local Bluetooth connectivity with system Bluetooth state.
 * <p/>
 * [ACTION_CONNECTION_STATE_CHANGED]
 * This action is used to keep track of the connection change on the target device. The purpose
 * is to synchronize the connection cycles of the local GATT connection and the system
 * Bluetooth
 * connection.
 * <p/>
 * [ACTION_BOND_STATE_CHANGED]
 * This action is used to keep track of the bond state change on the target device. The purpose
 * is to the connection cycles of the local GATT connection and the system Bluetooth
 * connection.
 * <p/>
 * [ACTION_KEYBOARD_UPDATE_CONFIRMED]
 * This action is used to receive the update confirmation from the user. The purpose is to
 * trigger DFU process.
 */
private void onHandleIntent(Context context, Intent intent) {
    final String action = intent.getAction();
    Log.d(TAG, "onHandleIntent: Received action: " + action);

    if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {

        if (!isBluetoothEnabled()) {
            Log.w(TAG, "onHandleIntent: Bluetooth connectivity not enabled");
            return;
        }

        // Match the connected device with the default keyboard name.
        Bundle extras = intent.getExtras();
        if (extras == null)
            return;
        final BluetoothDevice device = extras.getParcelable(BluetoothDevice.EXTRA_DEVICE);
        final int deviceConnectionState = extras.getInt(BluetoothAdapter.EXTRA_CONNECTION_STATE);

        Log.d(TAG, "onHandleIntent: " + device.getName() + " [" + device.getAddress() + "] change to state: "
                + deviceConnectionState);

        // Match the name of the target keyboard.
        if (!isTargetKeyboard(device))
            return;

        if (deviceConnectionState == BluetoothAdapter.STATE_CONNECTED) {
            // Prevent the second keyboard from using the service.
            if (isUpdateServiceInUse())
                return;

            obtainKeyboardInfo(device.getName(), device.getAddress());

            if (mDfuStatus != DFU_STATE_INFO_READY) {
                Log.w(TAG, "onHandleIntent: DFU preparation failed");
                changeDfuStatus(DFU_STATE_OBTAIN_INFO_ERROR);
                return;
            }

            showUpdateNotification();
        } else if (deviceConnectionState == BluetoothAdapter.STATE_DISCONNECTING) {
            handleGattDisconnection();
        }

    } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
        final int adapterState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
        if (adapterState == BluetoothAdapter.STATE_ON) {
            if (!isBluetoothEnabled())
                enableBluetoothConnectivity();
        } else if (adapterState == BluetoothAdapter.STATE_TURNING_OFF) {
            // Terminate update process and disable Bluetooth connectivity.
            disableBluetoothConnectivity();

            // Since BluetoothAdapter has been disabled, the callback of disconnection would not
            // be called. Therefore a separate clean-up of GATT connection is need.
            cleanUpGattConnection();
        }

    } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
        Bundle extras = intent.getExtras();
        if (extras == null)
            return;
        final BluetoothDevice device = extras.getParcelable(BluetoothDevice.EXTRA_DEVICE);
        final int deviceBondState = extras.getInt(BluetoothDevice.EXTRA_BOND_STATE);

        Log.d(TAG, "onHandleIntent: state change on device " + device.getName() + " [" + device.getAddress()
                + "], bond state: " + deviceBondState);

        if (!isTargetKeyboard(device))
            return;

        if (deviceBondState == BluetoothDevice.BOND_NONE) {
            handleGattDisconnection();
        }

    } else if (ACTION_KEYBOARD_UPDATE_CONFIRMED.equals(action)) {
        dismissUpdateNotification();

        if (mDfuStatus != DFU_STATE_INFO_READY || mDfuStatus == DFU_STATE_UPDATING) {
            Log.w(TAG, "onHandleIntent: DFP preparation not ready or DFU is in progress. ");
            changeDfuStatus(DFU_STATE_UPDATE_ABORTED);
            return;
        }

        String keyboardName = intent.getStringExtra(EXTRA_KEYBOARD_NAME);
        String keyboardAddress = intent.getStringExtra(EXTRA_KEYBOARD_ADDRESS);
        if (!mKeyboardName.equals(keyboardName) || !mKeyboardAddress.equals(keyboardAddress)) {
            Log.w(TAG, "onHandleIntent: No DFU service associated with " + keyboardName + " [" + keyboardAddress
                    + "]");
            return;
        }

        Log.d(TAG, "onHandleIntent: Start update process on " + keyboardName + " [" + keyboardAddress + "]");
        changeDfuStatus(DFU_STATE_SWITCHING_TO_DFU_MODE);

    } else if (ACTION_KEYBOARD_UPDATE_POSTPONED.equals(action)) {
        dismissUpdateNotification();
        // TODO(mcchou): Update the preference when the Settings keyboard entry is available.
    }
}

From source file:cn.edu.zju.bme319.cordova.ExtraInfo.java

    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) 
            throws JSONException {
        Activity activity = this.cordova.getActivity();
        context = (Context) this.context;
      /*  ww  w .  j  a va  2s  .  co  m*/
       // Register for broadcasts when a device is discovered
      IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
      context.registerReceiver(mReceiver, filter);
      
      
      // Register for broadcasts when discovery starts
      filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
      context.registerReceiver(mReceiver, filter);

      
      // Register for broadcasts when discovery has finished
      filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
      context.registerReceiver(mReceiver, filter);  
      
             
      // Register for broadcasts when connectivity state changes
      filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
      context.registerReceiver(mReceiver, filter);  
      
      Looper.prepare();

      found_devices = new ArrayList<BluetoothDevice>(); 
      
        if (btadapter == null) {
          btadapter = BluetoothAdapter.getDefaultAdapter();
        }

        if (action.equals("getExtra")) {
   
           callbackContext.success("123");
            return true;
        }
        else if (ACTION_DISCOVER_DEVICES.equals(action)) {
           try {
            
            Log.d("BluetoothPlugin", "We're in "+ACTION_DISCOVER_DEVICES);
            
            found_devices.clear();
            discovering=true;
            
              if (btadapter.isDiscovering()) {
                 btadapter.cancelDiscovery();
              }
              
              Log.i("BluetoothPlugin","Discovering devices...");        
            btadapter.startDiscovery();      
            
            while (discovering){}
            
            String devicesFound=null;
            int count=0;
            devicesFound="[";
            for (BluetoothDevice device : found_devices) {
               Log.i("BluetoothPlugin",device.getName() + " "+device.getAddress()+" "+device.getBondState());
               if ((device.getName()!=null) && (device.getBluetoothClass()!=null)){
                  devicesFound = devicesFound + " { \"name\" : \"" + device.getName() + "\" ," +
                        "\"address\" : \"" + device.getAddress() + "\" ," +
                     "\"class\" : \"" + device.getBluetoothClass().getDeviceClass() + "\" }";
                  if (count<found_devices.size()-1) devicesFound = devicesFound + ",";
               }else Log.i("BluetoothPlugin",device.getName() + " Problems retrieving attributes. Device not added ");
               count++;
            }   
            
            devicesFound= devicesFound + "] ";            
            
            Log.d("BluetoothPlugin - "+ACTION_DISCOVER_DEVICES, "Returning: "+ devicesFound);
            callbackContext.success(devicesFound);
            //result = new PluginResult(Status.OK, devicesFound);
         } catch (Exception Ex) {
            Log.d("BluetoothPlugin - "+ACTION_DISCOVER_DEVICES, "Got Exception "+ Ex.getMessage());
            callbackContext.error("discoveryError");
            //result = new PluginResult(Status.ERROR);
         }
         

//         try {
//            
//            Log.d("BluetoothPlugin", "We're in "+ACTION_DISCOVER_DEVICES);
//
//            // Create a BroadcastReceiver for ACTION_FOUND
////            final BroadcastReceiver mReceiver = new BroadcastReceiver() {
////                public void onReceive(Context context, Intent intent) {
////                    String action = intent.getAction();
////                    // When discovery finds a device
////                    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
////                        // Get the BluetoothDevice object from the Intent
////                        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
////                        // Add the name and address to an array adapter to show in a ListView
////                        mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
////                    }
////                }
////            };
////            // Register the BroadcastReceiver
////            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
////            registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
////            
////             // ??
////              if (btadapter.isDiscovering()) {
////                 btadapter.cancelDiscovery();
////                 Log.d("BluetoothPlugin", "We're in "+"12");
////              }
////              //?
////              Log.d("BluetoothPlugin", "We're in "+"1234");
////              btadapter.startDiscovery();
////              Log.d("BluetoothPlugin", "We're in "+"123456");
////               
////            found_devices.clear();
////            //discovering=true;
////            
////              //if (btadapter.isDiscovering()) {
////              //   btadapter.cancelDiscovery();
////              //}
////              
////            SendCommand(0);
////            
////              Log.i("BluetoothPlugin","Discovering devices...");        
////            //btadapter.startDiscovery();   
////            
////            while (discovering){}
////            
////            String devicesFound=null;
////            int count=0;
////            devicesFound="[";
////            for (BluetoothDevice device : found_devices) {
////               Log.i("BluetoothPlugin",device.getName() + " "+device.getAddress()+" "+device.getBondState());
////               if ((device.getName()!=null) && (device.getBluetoothClass()!=null)){
////                  devicesFound = devicesFound + " { \"name\" : \"" + device.getName() + "\" ," +
////                        "\"address\" : \"" + device.getAddress() + "\" ," +
////                     "\"class\" : \"" + device.getBluetoothClass().getDeviceClass() + "\" }";
////                  if (count<found_devices.size()-1) devicesFound = devicesFound + ",";
////               }else Log.i("BluetoothPlugin",device.getName() + " Problems retrieving attributes. Device not added ");
////               count++;
////            }   
////            
////            devicesFound= devicesFound + "] ";            
////            
////            Log.d("BluetoothPlugin - "+ACTION_DISCOVER_DEVICES, "Returning: "+ devicesFound);
////            callbackContext.success(devicesFound);
//            //result = new PluginResult(Status.OK, devicesFound);
//            return true;
//         } catch (Exception Ex) {
//            Log.d("BluetoothPlugin - "+ACTION_DISCOVER_DEVICES, "Got Exception "+ Ex.getMessage());
//            //result = new PluginResult(Status.ERROR);
//            callbackContext.error("discoverError");
//            return false;
//         }
         
      
      } else    if (ACTION_IS_BT_ENABLED.equals(action)) {
         try {                     
            Log.d("BluetoothPlugin", "We're in "+ACTION_IS_BT_ENABLED);
            
            boolean isEnabled = btadapter.isEnabled();
            
            Log.d("BluetoothPlugin - "+ACTION_IS_BT_ENABLED, "Returning "+ "is Bluetooth Enabled? "+isEnabled);
            callbackContext.success(""+isEnabled);
            //result = new PluginResult(Status.OK, isEnabled);
            return true;
         } catch (Exception Ex) {
            Log.d("BluetoothPlugin - "+ACTION_IS_BT_ENABLED, "Got Exception "+ Ex.getMessage());
            callbackContext.error("isBTEnabledError");
            //result = new PluginResult(Status.ERROR);
            return false;
         }
         
      } else    if (ACTION_ENABLE_BT.equals(action)) {
         try {                     
            Log.d("BluetoothPlugin", "We're in "+ACTION_ENABLE_BT);
            
            boolean enabled = false;
            
            Log.d("BluetoothPlugin", "Enabling Bluetooth...");
            
            if (btadapter.isEnabled())
            {
              enabled = true;
            } else {
              enabled = btadapter.enable();
            }

            
            Log.d("BluetoothPlugin - "+ACTION_ENABLE_BT, "Returning "+ "Result: "+enabled);
            callbackContext.success("" + enabled);
            //result = new PluginResult(Status.OK, enabled);
            return true;
         } catch (Exception Ex) {
            Log.d("BluetoothPlugin - "+ACTION_ENABLE_BT, "Got Exception "+ Ex.getMessage());
            callbackContext.error("EnableBTError");
            //result = new PluginResult(Status.ERROR);
            return false;
         }         
         
      } else    if (ACTION_DISABLE_BT.equals(action)) {
         try {                     
            Log.d("BluetoothPlugin", "We're in "+ACTION_DISABLE_BT);
            
            boolean disabled = false;
            
            Log.d("BluetoothPlugin", "Disabling Bluetooth...");
            
            if (btadapter.isEnabled())
            {
               disabled = btadapter.disable();
            } else {
               disabled = true;
            }            
                        
            Log.d("BluetoothPlugin - "+ACTION_DISABLE_BT, "Returning "+ "Result: "+disabled);
            callbackContext.success("" + disabled);
            //result = new PluginResult(Status.OK, disabled);
            return true;
         } catch (Exception Ex) {
            Log.d("BluetoothPlugin - "+ACTION_DISABLE_BT, "Got Exception "+ Ex.getMessage());
            callbackContext.error("DisableBTError");
            //result = new PluginResult(Status.ERROR);
            return false;
         }
               
      } else    if (ACTION_PAIR_BT.equals(action)) {
         try {                     
            Log.d("BluetoothPlugin", "We're in "+ACTION_PAIR_BT);
            
            String addressDevice = args.getString(0);
            
            if (btadapter.isDiscovering()) {
                 btadapter.cancelDiscovery();
              }

            BluetoothDevice device = btadapter.getRemoteDevice(addressDevice);
            boolean paired = false;
                     
            Log.d("BluetoothPlugin","Pairing with Bluetooth device with name " + device.getName()+" and address "+device.getAddress());
                   
            try {
               Method m = device.getClass().getMethod("createBond");
               paired = (Boolean) m.invoke(device);               
            } catch (Exception e) 
            {
               e.printStackTrace();
            }  
            
            
            Log.d("BluetoothPlugin - "+ACTION_PAIR_BT, "Returning "+ "Result: "+paired);
            callbackContext.success("" + paired);
            //result = new PluginResult(Status.OK, paired);
            return true;
         } catch (Exception Ex) {
            Log.d("BluetoothPlugin - "+ACTION_PAIR_BT, "Got Exception "+ Ex.getMessage());
            callbackContext.error("pairBTError");
            //result = new PluginResult(Status.ERROR);
            return false;
         }
         
                  
      } else    if (ACTION_UNPAIR_BT.equals(action)) {
         try {                     
            Log.d("BluetoothPlugin", "We're in "+ACTION_UNPAIR_BT);
            
            String addressDevice = args.getString(0);
            
            if (btadapter.isDiscovering()) {
                 btadapter.cancelDiscovery();
              }

            BluetoothDevice device = btadapter.getRemoteDevice(addressDevice);
            boolean unpaired = false;
                     
            Log.d("BluetoothPlugin","Unpairing Bluetooth device with " + device.getName()+" and address "+device.getAddress());
                   
            try {
               Method m = device.getClass().getMethod("removeBond");
               unpaired = (Boolean) m.invoke(device);               
            } catch (Exception e) 
            {
               e.printStackTrace();
            }  
            
            
            Log.d("BluetoothPlugin - "+ACTION_UNPAIR_BT, "Returning "+ "Result: "+unpaired);
            callbackContext.success("" + unpaired);
            //result = new PluginResult(Status.OK, unpaired);
            return true;
         } catch (Exception Ex) {
            Log.d("BluetoothPlugin - "+ACTION_UNPAIR_BT, "Got Exception "+ Ex.getMessage());
            callbackContext.error("unpairBTError");
            //result = new PluginResult(Status.ERROR);
            return false;
         }
                     
      } else    if (ACTION_LIST_BOUND_DEVICES.equals(action)) {
         try {                     
            Log.d("BluetoothPlugin", "We're in "+ACTION_LIST_BOUND_DEVICES);
            
            Log.d("BluetoothPlugin","Getting paired devices...");
            //?
            Set<BluetoothDevice> pairedDevices = btadapter.getBondedDevices();
            int count =0;   
            String resultBoundDevices="[ ";
            if (pairedDevices.size() > 0) {               
               for (BluetoothDevice device : pairedDevices) 
               {                  
                  Log.i("BluetoothPlugin",device.getName() + " "+device.getAddress()+" "+device.getBondState());
                  
                  if ((device.getName()!=null) && (device.getBluetoothClass()!=null)){
                     resultBoundDevices = resultBoundDevices + " { \"name\" : \"" + device.getName() + "\" ," +
                           "\"address\" : \"" + device.getAddress() + "\" ," +
                           "\"class\" : \"" + device.getBluetoothClass().getDeviceClass() + "\" }";
                      if (count<pairedDevices.size()-1) resultBoundDevices = resultBoundDevices + ",";                  
                  } else Log.i("BluetoothPlugin",device.getName() + " Problems retrieving attributes. Device not added ");
                   count++;
                }             
               
            }
            
            resultBoundDevices= resultBoundDevices + "] ";
            
            Log.d("BluetoothPlugin - "+ACTION_LIST_BOUND_DEVICES, "Returning "+ resultBoundDevices);
            callbackContext.success("" + resultBoundDevices);
            //result = new PluginResult(Status.OK, resultBoundDevices);
            return true;
         } catch (Exception Ex) {
            Log.d("BluetoothPlugin - "+ACTION_LIST_BOUND_DEVICES, "Got Exception "+ Ex.getMessage());
            callbackContext.error("resultBoundDevicesError");
            //result = new PluginResult(Status.ERROR);
            return false;
         }   
            
         
      } else    if (ACTION_STOP_DISCOVERING_BT.equals(action)) {
         try {                     
            Log.d("BluetoothPlugin", "We're in "+ACTION_STOP_DISCOVERING_BT);
            
            boolean stopped = true;
            
            Log.d("BluetoothPlugin", "Stop Discovering Bluetooth Devices...");
            
            if (btadapter.isDiscovering())
            {
               Log.i("BluetoothPlugin","Stop discovery...");   
               stopped = btadapter.cancelDiscovery();
                 discovering=false;
            }            
            
         
            Log.d("BluetoothPlugin - "+ACTION_STOP_DISCOVERING_BT, "Returning "+ "Result: "+stopped);
            callbackContext.success("" + stopped);
            //result = new PluginResult(Status.OK, stopped);
            return true;
         } catch (Exception Ex) {
            Log.d("BluetoothPlugin - "+ACTION_STOP_DISCOVERING_BT, "Got Exception "+ Ex.getMessage());
            callbackContext.error("stoppedError");
            //result = new PluginResult(Status.ERROR);
            return false;
         }
         
         
      } else    if (ACTION_IS_BOUND_BT.equals(action)) {
         try {                     
            Log.d("BluetoothPlugin", "We're in "+ACTION_IS_BOUND_BT);
            String addressDevice = args.getString(0);
            BluetoothDevice device = btadapter.getRemoteDevice(addressDevice);
            Log.i("BluetoothPlugin","BT Device in state "+device.getBondState());   
            
            boolean state = false;
            
            if (device!=null && device.getBondState()==12) 
               state =  true;
            else
               state = false;
            
            Log.d("BluetoothPlugin","Is Bound with " + device.getName()+" - address "+device.getAddress());                         
            
            Log.d("BluetoothPlugin - "+ACTION_IS_BOUND_BT, "Returning "+ "Result: "+state);
            callbackContext.success("" + state);
            //result = new PluginResult(Status.OK, state);
            return true;   
         } catch (Exception Ex) {
            Log.d("BluetoothPlugin - "+ACTION_IS_BOUND_BT, "Got Exception "+ Ex.getMessage());
            callbackContext.error("boundBTError");
            //result = new PluginResult(Status.ERROR);
            return false;
         }      
      
      
      } else if(ACTION_BT_CONNECT.equals(action)){
         try
         {
            Log.d("BluetoothPlugin", "We're in "+ACTION_BT_CONNECT);
            deviceAddress = "8C:DE:52:99:26:23";
            Log.d("BluetoothPlugin", "We're in "+deviceAddress);
            BluetoothDevice device = btadapter.getRemoteDevice(deviceAddress);
            
            //m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
            //bluetoothSocket = (BluetoothSocket) m.invoke(device, Integer.valueOf(1));
            //SendCommand(0);
            // ??socket
            try {
               bluetoothSocket = device.createRfcommSocketToServiceRecord(UUID
                     .fromString(MY_UUID));
            } catch (IOException e) {
               //Toast.makeText(this, "?", Toast.LENGTH_SHORT).show();
            }
            bluetoothSocket.connect();
            sendCommandFlag = 0;
            SendCommand(sendCommandFlag);
            
            
            
            if(bluetoothSocket.isConnected())
            {
               this.isConnection = true;
               String str = "";
               // 
               try {
                  inputStream = bluetoothSocket.getInputStream(); // ???
                  str = ""+1;
               } catch (IOException e) {
                  //Toast.makeText(this, "??", Toast.LENGTH_SHORT).show();
                  //return;
                  str=""+2;
               }
               if (bThread == false) {
                  ReadThread.start();
                  bThread = true;
                  str = ""+3;
               } else {
                  bRun = true;
                  str = ""+4;
               }
               
               //result = new PluginResult(Status.OK, str);
                //result.setKeepCallback(true);
                    // callbackContext.sendPluginResult(result);
               callbackContext.success("" + str);
            }
            else {
               //result = new PluginResult(Status.OK, "failure");
               callbackContext.error("Could not connect to ");

            }
            return true;
         } catch (Exception Ex)
         {
            // TODO: handle exception
            Log.d("BluetoothPlugin - "+ACTION_BT_CONNECT, "Got Exception "+ Ex.getMessage());
            //result = new PluginResult(Status.ERROR);
            callbackContext.error("Could not connect to ");
            return false;
         }
      }else if(ACTION_BT_GETDATA.equals(action)){
         try
         {
            Log.d("BluetoothPlugin", "We're in "+ACTION_BT_GETDATA);
            sendCommandFlag = 1;
            SendCommand(sendCommandFlag);   
//            if (bluetoothSocket != null) {
//                  if(bluetoothSocket.isConnected()){
//                     SendCommand(1);   
//                  }
//            }
//               
            //result = new PluginResult(Status.OK, spoValue);
            Log.v("Get1 ", returnBTData);
            while(returnBTData == "")
            {
               Log.v("Get2 ", returnBTData);
            }
            Log.v("Get3 ", returnBTData);
            callbackContext.success("" + returnBTData);
            //ReadThread.cancel();
            
            bluetoothSocket.close();
            bluetoothSocket = null;
            
            return true;
         } catch (Exception Ex)
         {
            // TODO: handle exception
            Log.d("BluetoothPlugin - "+ACTION_BT_GETDATA, "Got Exception "+ Ex.getMessage());
            callbackContext.error("" + "getDataError");
            //result = new PluginResult(Status.ERROR);
            return false;
         }
      }
      
      else {
//         result = new PluginResult(Status.INVALID_ACTION);
//         Log.d("BluetoothPlugin", "Invalid action : "+action+" passed");
//         return result;
         callbackContext.error("" + "actionError");
      }
        return false;
    }

From source file:com.bluetooth.mwoolley.microbitbledemo.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    setButtonText();//from w w w. ja v  a 2  s. com
    getSupportActionBar().setTitle(R.string.screen_title_main);
    showMsg(Utility.htmlColorGreen("Ready"));

    Settings.getInstance().restore(this);

    ble_device_list_adapter = new ListAdapter();

    ListView listView = (ListView) this.findViewById(R.id.deviceList);
    listView.setAdapter(ble_device_list_adapter);

    registerReceiver(broadcastReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));

    ble_scanner = BleScannerFactory.getBleScanner(this.getApplicationContext());
    ble_scanner.setDevice_name_start(DEVICE_NAME_START);
    ble_scanner.setSelect_bonded_devices_only(true);

    listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            if (ble_scanning) {
                setScanState(false);
                ble_scanner.stopScanning();
            }

            BluetoothDevice device = ble_device_list_adapter.getDevice(position);
            if (device.getBondState() == BluetoothDevice.BOND_NONE
                    && Settings.getInstance().isFilter_unpaired_devices()) {
                device.createBond();
                showMsg(Utility.htmlColorRed("Selected micro:bit must be paired - pairing now"));
                return;
            }
            try {
                MainActivity.this.unregisterReceiver(broadcastReceiver);
            } catch (Exception e) {
                // ignore!
            }
            if (toast != null) {
                toast.cancel();
            }
            MicroBit microbit = MicroBit.getInstance();
            microbit.setBluetooth_device(device);
            Intent intent = new Intent(MainActivity.this, MenuActivity.class);
            intent.putExtra(MenuActivity.EXTRA_NAME, device.getName());
            intent.putExtra(MenuActivity.EXTRA_ID, device.getAddress());
            startActivity(intent);

        }
    });
}

From source file:com.cypress.cysmart.CommonFragments.ProfileScanningFragment.java

/**
 * Method to connect to the device selected. The time allotted for having a
 * connection is 8 seconds. After 8 seconds it will disconnect if not
 * connected and initiate scan once more
 *
 * @param device//from  w  ww .  j  a v a 2  s.com
 */

void connectDevice(BluetoothDevice device) {
    // Register the broadcast receiver for connection status
    if (!receiverEnabled) {
        Logger.e("Registering receiver some how ");
        getActivity().registerReceiver(mGattUpdateReceiver, Utils.makeGattUpdateIntentFilter());
        receiverEnabled = true;
    }
    mpdia.setTitle(getResources().getString(R.string.alert_message_connect_title));

    mpdia.setMessage(getResources().getString(R.string.alert_message_connect) + "\n" + device.getName() + "\n"
            + device.getAddress() + "\n" + getResources().getString(R.string.alert_message_wait));

    if (!getActivity().isDestroyed() && mpdia != null) {
        mpdia.show();
    }
    mDeviceAddress = device.getAddress();
    mDeviceName = device.getName();
    // Get the connection status of the device
    if (BluetoothLeService.getConnectionState() == BluetoothLeService.STATE_DISCONNECTED) {
        Logger.i("BluetoothLeService.getConnectionState()--->" + BluetoothLeService.getConnectionState());
        // Disconnected,so connect
        HANDLER_FLAG = true;
        BluetoothLeService.connect(mDeviceAddress, mDeviceName, getActivity());
    } else {
        Logger.i("BluetoothLeService.getConnectionState()--->" + BluetoothLeService.getConnectionState());
        // Connecting to some devices,so disconnect and then connect
        BluetoothLeService.disconnect();
        HANDLER_FLAG = true;
        BluetoothLeService.connect(mDeviceAddress, mDeviceName, getActivity());
    }
    mConnectHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Logger.e("Connect handler called");
            if (HANDLER_FLAG) {
                mpdia.dismiss();
                BluetoothLeService.disconnect();
                try {
                    Toast.makeText(getActivity(), R.string.profile_control_delay_message, Toast.LENGTH_SHORT)
                            .show();
                    if (mLeDeviceListAdapter != null)
                        mLeDeviceListAdapter.clear();
                    if (mLeDeviceListAdapter != null) {
                        try {
                            mLeDeviceListAdapter.notifyDataSetChanged();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    // mswipeLayout.setVisibility(View.INVISIBLE);
                    // mNoDeviceFound.setVisibility(View.VISIBLE);
                    scanLeDevice(true);
                    mScanning = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }, 10000);

}

From source file:com.nbplus.iotapp.bluetooth.BluetoothLeService.java

/**
 * for log./*from  w  w  w.ja v a 2  s.  co m*/
 * @param device
 * @param adRecords
 */
private void printScanDevices(BluetoothDevice device, HashMap<Integer, AdRecord> adRecords) {
    Log.d(TAG, "onLeScan() =============================================");
    Log.d(TAG, "onLeScan: uuid:" + (device.getUuids() != null ? device.getUuids().toString() : "null")
            + ", name = " + device.getName());
    Log.d(TAG, "onLeScan: address:" + device.getAddress());
    Log.d(TAG, "onLeScan: bluetooth class:" + device.getBluetoothClass());
    Log.d(TAG, "onLeScan: type:" + device.getType());

    String str = "";
    byte[] values;

    for (Map.Entry<Integer, AdRecord> entry : adRecords.entrySet()) {
        Integer type = entry.getKey();
        AdRecord adRecord = entry.getValue();

        if (adRecord != null) {
            switch (type) {
            case AdRecord.TYPE_FLAGS:
                int flags = adRecord.getValue()[0] & 0x0FF;
                str = "";
                if ((flags & 0x01) > 0) {
                    str += "'LE Limited Discoverable Mode' ";
                }
                if ((flags & (0x01 << 1)) > 0) {
                    str += "'LE General Discoverable Mode' ";
                }
                if ((flags & (0x01 << 2)) > 0) {
                    str += "'BR/EDR Not Supported' ";
                }
                if ((flags & (0x01 << 3)) > 0) {
                    str += "'Simultaneous LE and BR/EDR to Same Device Capacble (Controller)' ";
                }
                if ((flags & (0x01 << 4)) > 0) {
                    str += "'Simultaneous LE and BR/EDR to Same Device Capacble (Host)' ";
                }

                Log.d(TAG, "onLeScan: TYPE_FLAGS = " + str);
                break;

            case AdRecord.TYPE_UUID16_INC:
            case AdRecord.TYPE_UUID16: {
                ArrayList<String> uuids = DataParser.getUint16StringArray(adRecord.getValue());
                int i = 0;
                for (String uuid : uuids) {
                    Log.d(TAG, "onLeScan: TYPE_UUID16(_INC)[" + (++i) + "] = " + uuid);
                }
                break;
            }
            case AdRecord.TYPE_UUID32_INC:
            case AdRecord.TYPE_UUID32: {
                ArrayList<String> uuids = DataParser.getUint32StringArray(adRecord.getValue());
                int i = 0;
                for (String uuid : uuids) {
                    Log.d(TAG, "onLeScan: TYPE_UUID32(_INC)[" + (++i) + "] = " + uuid);
                }
                break;
            }

            case AdRecord.TYPE_UUID128_INC:
            case AdRecord.TYPE_UUID128: {
                ArrayList<String> uuids = DataParser.getUint128StringArray(adRecord.getValue());
                int i = 0;
                for (String uuid : uuids) {
                    Log.d(TAG, "onLeScan: TYPE_UUID128(_INC)[" + (++i) + "] = " + uuid);
                }
                break;
            }

            case AdRecord.TYPE_NAME_SHORT:
                str = DataParser.getString(adRecord.getValue());
                Log.d(TAG, "onLeScan: TYPE_NAME_SHORT = " + str);
                break;

            case AdRecord.TYPE_NAME:
                str = DataParser.getString(adRecord.getValue());
                Log.d(TAG, "onLeScan: TYPE_NAME = " + str);
                break;

            case AdRecord.TYPE_TRANSMITPOWER:
                Log.d(TAG, "onLeScan: TYPE_TRANSMITPOWER = " + DataParser.getInt8(adRecord.getValue()[0]));
                break;

            case AdRecord.TYPE_SERVICEDATA:
                values = adRecord.getValue();
                String uuid = DataParser.getUint16String(Arrays.copyOfRange(values, 0, 2));
                Log.d(TAG, "onLeScan: TYPE_SERVICEDATA uuid = " + uuid);
                str = DataParser.getHexString(Arrays.copyOfRange(values, 2, values.length));
                Log.d(TAG, "onLeScan: TYPE_SERVICEDATA hexstringdata = " + str);
                break;

            case AdRecord.TYPE_APPEARANCE:
                str = DataParser.getUint16String(adRecord.getValue());
                Log.d(TAG, "onLeScan: TYPE_APPEARANCE = " + str);
                break;

            case AdRecord.TYPE_VENDOR_SPECIFIC:
                values = adRecord.getValue();
                // https://www.bluetooth.org/en-us/specification/assigned-numbers/company-identifiers
                str = DataParser.getUint16String(Arrays.copyOfRange(values, 0, 2));
                Log.d(TAG, "onLeScan: TYPE_VENDOR_SPECIFIC company = " + str);
                if ("004C".equals(str)) { // Apple Inc
                    int offset = 2;
                    int data_type = values[offset++];
                    int data_length = values[offset++];
                    if (data_type == 0x02) { // iBeacon
                        // https://www.uncinc.nl/nl/blog/finding-out-the-ibeacons-specifications
                        // http://www.warski.org/blog/2014/01/how-ibeacons-work/
                        // http://developer.iotdesignshop.com/tutorials/bluetooth-le-and-ibeacon-primer/

                        //                                            String uuid = parseUUID(this.parseHex(Arrays.copyOfRange(value, offset, offset + 16), true));
                        //                                            offset += 16;
                        //                                            ad.apple.ibeacon.major = parseHex(Arrays.copyOfRange(value, offset, offset + 2), true);
                        //                                            offset += 2;
                        //                                            ad.apple.ibeacon.minor = parseHex(Arrays.copyOfRange(value, offset, offset + 2), true);
                        //                                            offset += 2;
                        //                                            ad.tx_power = this.parseSignedNumber(value[offset]);
                    } else {
                        //                                            ad.apple.vendor = this.parseHex(Arrays.copyOfRange(value, offset - 2, offset + data_length), true);
                    }
                } else {
                    //                                        ad.vendor = this.parseHex(Arrays.copyOfRange(value, i, i + len - 1), true);
                }
                break;

            }
        }
    }

    Log.d(TAG, "=============================================");
}

From source file:com.zologic.tardis.app.MainActivity.java

private void showChooseDeviceServiceDialog(final BluetoothDevice device) {
    // Prepare dialog
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    String deviceName = device.getName();
    String title = String.format(getString(R.string.scan_connectto_dialog_title_format),
            deviceName != null ? deviceName : device.getAddress());
    String[] items = new String[kComponentsNameIds.length];
    for (int i = 0; i < kComponentsNameIds.length; i++)
        items[i] = getString(kComponentsNameIds[i]);

    builder.setTitle(title).setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            switch (kComponentsNameIds[which]) {
            case R.string.scan_connectservice_info: { // Info
                mComponentToStartWhenConnected = InfoActivity.class;
                break;
            }//from   ww  w. j  av  a 2s.com
            case R.string.scan_connectservice_uart: { // Uart
                mComponentToStartWhenConnected = UartActivity.class;
                break;
            }
            case R.string.scan_connectservice_pinio: { // PinIO
                mComponentToStartWhenConnected = PinIOActivity.class;
                break;
            }
            case R.string.scan_connectservice_controller: { // Controller
                mComponentToStartWhenConnected = ControllerActivity.class;
                break;
            }
            case R.string.scan_connectservice_beacon: { // Beacon
                mComponentToStartWhenConnected = BeaconActivity.class;
                break;
            }
            }

            if (mComponentToStartWhenConnected != null) {
                connect(device); // First connect to the device, and when connected go to selected activity
            }
        }
    });

    // Show dialog
    AlertDialog dialog = builder.create();
    dialog.show();
}

From source file:com.example.nachiketvatkar.locateus.BluetoothPairing.java

private void showChooseDeviceServiceDialog(final BluetoothDevice device) {
    // Prepare dialog
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    String deviceName = device.getName();
    String title = String.format(getString(R.string.scan_connectto_dialog_title_format),
            deviceName != null ? deviceName : device.getAddress());
    String[] items = new String[kComponentsNameIds.length];
    for (int i = 0; i < kComponentsNameIds.length; i++) {
        items[i] = getString(kComponentsNameIds[i]);
    }// ww w .ja va 2s.  c o  m
    builder.setTitle(title).setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            switch (kComponentsNameIds[which]) {
            case R.string.scan_connectservice_info: { // Info
                //                                mComponentToStartWhenConnected = InfoActivity.class;
                break;
            }
            case R.string.scan_connectservice_uart: { // Uart
                //                                mComponentToStartWhenConnected = UartActivity.class;
                break;
            }
            case R.string.scan_connectservice_pinio: { // PinIO
                //                                mComponentToStartWhenConnected = PinIOActivity.class;
                break;
            }
            case R.string.scan_connectservice_controller: { // Controller
                //                                mComponentToStartWhenConnected = ControllerActivity.class;
                break;
            }
            case R.string.scan_connectservice_beacon: { // Beacon
                //                                mComponentToStartWhenConnected = BeaconActivity.class;
                break;
            }
            }

            if (mComponentToStartWhenConnected != null) {
                connect(device);// First connect to the device, and when connected go to selected activity
            }
        }
    });
    // Show dialog
    AlertDialog dialog = builder.create();
    dialog.show();
}

From source file:com.cs4644.vt.theonering.MainActivity.java

private void showChooseDeviceServiceDialog(final BluetoothDevice device) {
    // Prepare dialog
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    String deviceName = device.getName();
    String title = String.format(getString(R.string.scan_connectto_dialog_title_format),
            deviceName != null ? deviceName : device.getAddress());
    String[] items = new String[kComponentsNameIds.length];
    for (int i = 0; i < kComponentsNameIds.length; i++)
        items[i] = getString(kComponentsNameIds[i]);

    builder.setTitle(title).setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            switch (kComponentsNameIds[which]) {
            //                            case R.string.scan_connectservice_info: {          // Info
            //                                mComponentToStartWhenConnected = InfoActivity.class;
            //                                break;
            //                            }
            case R.string.scan_connectservice_uart: { // Uart
                //                                mComponentToStartWhenConnected = UartActivity.class;
                mComponentToStartWhenConnected = ControllerActivity.class;
                break;
            }/*from  w  ww  .j  ava 2s . com*/
            //                            case R.string.scan_connectservice_pinio: {        // PinIO
            //                                mComponentToStartWhenConnected = PinIOActivity.class;
            //                                break;
            //                            }
            //                            case R.string.scan_connectservice_controller: {     // Controller
            //                                mComponentToStartWhenConnected = adafruit.bluefruit.le.connect.app.ControllerActivity.class;
            //                                break;
            //                            }
            //                            case R.string.scan_connectservice_beacon: {         // Beacon
            //                                mComponentToStartWhenConnected = BeaconActivity.class;
            //                                break;
            //                            }
            }

            if (mComponentToStartWhenConnected != null) {
                connect(device); // First connect to the device, and when connected go to selected activity
            }
        }
    });

    // Show dialog
    AlertDialog dialog = builder.create();
    dialog.show();
}