/**
   * Create a bluetooth connection with SerialPortServiceClass_UUID
   *
   * @see <a href= "http://lejos.sourceforge.net/forum/viewtopic.php?t=1991&highlight=android" /> On
   *     error the method either sends a message to it's owner or creates an exception in the case
   *     of no message handler.
   */
  public void createNXTconnection() throws IOException {
    try {
      BluetoothSocket nxtBTSocketTemporary;
      BluetoothDevice nxtDevice = null;
      nxtDevice = btAdapter.getRemoteDevice(mMACaddress);
      if (nxtDevice == null) {
        if (uiHandler == null) throw new IOException();
        else {
          sendToast(mResources.getString(R.string.no_paired_nxt));
          sendState(STATE_CONNECTERROR);
          return;
        }
      }
      nxtBTSocketTemporary =
          nxtDevice.createRfcommSocketToServiceRecord(SERIAL_PORT_SERVICE_CLASS_UUID);
      try {
        nxtBTSocketTemporary.connect();
      } catch (IOException e) {
        if (myOwner.isPairing()) {
          if (uiHandler != null) {
            sendToast(mResources.getString(R.string.pairing_message));
            sendState(STATE_CONNECTERROR_PAIRING);
          } else throw e;
          return;
        }

        // try another method for connection, this should work on the HTC desire, credits to Michael
        // Biermann
        try {
          Method mMethod =
              nxtDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
          nxtBTSocketTemporary = (BluetoothSocket) mMethod.invoke(nxtDevice, Integer.valueOf(1));
          nxtBTSocketTemporary.connect();
        } catch (Exception e1) {
          if (uiHandler == null) throw new IOException();
          else sendState(STATE_CONNECTERROR);
          return;
        }
      }
      nxtBTsocket = nxtBTSocketTemporary;
      nxtInputStream = nxtBTsocket.getInputStream();
      nxtOutputStream = nxtBTsocket.getOutputStream();
      connected = true;
    } catch (IOException e) {
      if (uiHandler == null) throw e;
      else {
        if (myOwner.isPairing()) sendToast(mResources.getString(R.string.pairing_message));
        sendState(STATE_CONNECTERROR);
        return;
      }
    }
    // everything was OK
    if (uiHandler != null) sendState(STATE_CONNECTED);
  }
 public void run() {
   bluetoothAdapter.cancelDiscovery();
   try {
     Log.d(TAG, "About to connect");
     socket.connect();
     Log.d(TAG, "Connected");
     synchronized (this) {
       communicator = communicatorService.createCommunicatorThread(socket);
     }
     new Thread(
             new Runnable() {
               @Override
               public void run() {
                 Log.d(TAG, "Start");
                 communicator.startCommunication();
               }
             })
         .start();
   } catch (IOException connectException) {
     try {
       socket.close();
     } catch (IOException closeException) {
       Log.d(TAG, closeException.getLocalizedMessage());
     }
   }
 }
예제 #3
0
    @Override
    public void run() {
      Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
      setName("ConnectThread" + mSocketType);

      // Always cancel discovery because it will slow down a connection
      boolean t = false;
      t = mAdapter.cancelDiscovery();
      if (t == false) t = true;

      try {

        // Make a connection to the BluetoothSocket
        // This is a blocking call and will only return on a
        // successful connection or an exception
        mmSocket.connect();
      } catch (IOException e) {
        // Close the socket
        try {
          mmSocket.close();
        } catch (IOException e2) {
          Log.e(TAG, "unable to close() " + mSocketType + " socket during connection failure", e2);
        }
        connectionFailed();
        return;
      }

      // Reset the ConnectThread because we're done
      synchronized (BluetoothService.this) {
        mConnectThread = null;
      }

      // Start the connected thread
      connected(mmSocket, mmDevice, mSocketType);
    }
예제 #4
0
    @Override
    public void run() {
      //			adapter.cancelDiscovery();
      isRunning = true;
      cancelled = false;

      int loopCount = 0;
      BluetoothSocket tmpSocket = null;
      while (true) {
        tmpSocket = null;

        // Break out if this was cancelled.
        if (cancelled) {
          break;
        }

        // Get the device socket.
        try {
          tmpSocket = device.createRfcommSocketToServiceRecord(UUID_RFCOMM_GENERIC);
        } catch (SecurityException e) {
          e.printStackTrace();
        } catch (IllegalArgumentException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }

        // Try to connect to the socket.
        try {
          tmpSocket.connect();
          // threadHandler.sendEmptyMessage(MSG_CONNECTED);
          break;
        } catch (IOException connectException) {
          try {
            tmpSocket.close();
          } catch (IOException closeException) {
          }
        }

        // Wait to try to connect to the device again.
        int sleepSeconds = (int) (((loopCount / 5) + 1) * 1.5);
        sleepSeconds = (sleepSeconds > 10) ? 10 : sleepSeconds;
        //				Log.v(TAG, "\tFailed to connect, will try again in "+ sleepSeconds +" sec.");
        try {
          Thread.sleep(sleepSeconds * 1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }

        loopCount++;
      }

      isRunning = false;

      // Tell the main thread to manage the socket.
      if (tmpSocket != null) {
        mSsocket = tmpSocket;
        mThreadHandler.sendEmptyMessage(MSG_MANAGE_SOCKET);
      }
    }
    @Override
    public void run() {
      if (DEBUG) {
        Log.d(TAG, "ConnectThread.run() | SocketType:" + mSocketType);
      }
      setName("ConnectThread" + mSocketType);

      // Always cancel discovery because it will slow down a connection
      mAdapter.cancelDiscovery();

      // Make a connection to the BluetoothSocket
      try {
        // This is a blocking call and will only return on a
        // successful connection or an exception
        mmSocket.connect();

      } catch (IOException e) {
        Log.e(TAG, "ConnectThread.run " + e);
        // Close the socket
        closeSocket();
        connectionFailed();
        return;
      }

      // Reset the ConnectThread because we're done
      synchronized (BluetoothService.this) {
        mConnectThread = null;
      }

      // Start the connected thread
      connected(mmSocket, mmDevice, mSocketType);
    }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    digitalPinsButton = (Button) findViewById(R.id.button_digital_pins);
    analogPinsButton = (Button) findViewById(R.id.button_analog_pins);

    Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBTIntent, REQUEST_ENABLE_BT);

    BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

    try {

      BluetoothDevice device = bluetooth.getRemoteDevice(BLUETOOTH_DEVICE_ADDRESS);

      Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});

      clientSocket = (BluetoothSocket) m.invoke(device, 1);
      clientSocket.connect();

    } catch (Exception e) {
      Log.d("BLUETOOTH", e.getMessage());
    }

    Toast.makeText(getApplicationContext(), "CONNECTED", Toast.LENGTH_LONG).show();
  }
    public void run() {

      // Always cancel discovery because it will slow down a connection
      mBluetoothAdapter.cancelDiscovery();

      // Make a connection to the BluetoothSocket
      try {
        // This is a blocking call and will only return on a
        // successful connection or an exception
        mmSocket.connect();
      } catch (IOException e) {
        connectionFailed();
        // Close the socket
        try {
          mmSocket.close();
        } catch (IOException e2) {
        }
        return;
      }

      // Reset the ConnectThread-connection ok
      synchronized (MainActivity.this) {
        mConnectThread = null;
      }
      // Start the connected thread
      connected(mmSocket, mmDevice);
    }
예제 #8
0
    @Override
    public void run() {
      timestamp = System.currentTimeMillis();

      BluetoothSocket btSocket = null;
      try {
        btSocket =
            device.createInsecureRfcommSocketToServiceRecord(BluetoothUuid_ObexMns.getUuid());
        btSocket.connect();
      } catch (IOException e) {
        Log.e(TAG, "BtSocket Connect error " + e.getMessage(), e);
        markConnectionFailed(btSocket);
        return;
      }

      if (V)
        Log.v(
            TAG,
            "Rfcomm socket connection attempt took "
                + (System.currentTimeMillis() - timestamp)
                + " ms");
      ObexTransport transport;
      transport = new BluetoothMnsRfcommTransport(btSocket);
      if (V) Log.v(TAG, "Send transport message " + transport.toString());

      mSessionHandler.obtainMessage(RFCOMM_CONNECTED, transport).sendToTarget();
    }
예제 #9
0
    public void run() {
      InputStream inStream = null;
      OutputStream outStream = null;
      mBluetoothAdapter.cancelDiscovery();

      try {
        mySocket.connect();
      } catch (IOException e) {
        Log.e("Bluetooth", mDevice.getName() + ": Could not establish connection with device");
        try {
          mySocket.close();
        } catch (IOException e1) {
          Log.e("Bluetooth", mDevice.getName() + ": could not close socket", e1);
        }
      }

      String line = "";
      try {
        inStream = mySocket.getInputStream();
        outStream = mySocket.getOutputStream();

        outStream.write(message.getBytes());
        outStream.flush();
        Log.e("Bluetooth", "Message sent: " + message);
        inStream.close();
        outStream.close();
        cancel();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
예제 #10
0
    public void run() {
      // Log.v("DistoX", "sync ConnectingThread run");
      setName("ConnectingThread");
      mAdapter.cancelDiscovery(); // Always cancel discovery because it will slow down a connection

      try { // Make a connection to the BluetoothSocket
        mmSocket.connect(); // blocking call
      } catch (IOException e) {
        connectionFailed();
        try { // Close the socket
          mmSocket.close();
        } catch (IOException e2) {
          TopoDroidLog.Log(
              TopoDroidLog.LOG_ERR, "unable to close() socket during connection failure " + e2);
        }
        // SyncService.this.start(); // Start the service over to restart listening mode
        return;
      }

      synchronized (SyncService.this) { // Reset the ConnectingThread because we're done
        mConnectingThread = null;
      }

      connected(mmSocket, mmDevice); // Start the connected thread
      // TopoDroidLog.Log( TopoDroidLog.LOG_SYNC, "sync connecting thread done");
    }
예제 #11
0
 // Begin Bluetooth connection
 public void run() {
   Log.w(TAG, "ConnectionThread - run()");
   // Cancel discovery because it will slow down the connection
   connectAdapter.cancelDiscovery();
   try {
     // Connect through the socket will block until it succeeds or throws an exception
     connectSocket.connect();
   } catch (IOException connectException) {
     // Unable to connect; close the socket and get out
     try {
       connectSocket.close();
       // If connection fail less than 2 times
       Log.w(TAG, "Connection fail " + count + 1 + " times");
       if (count < 2) {
         count++;
         beginConnection();
       }
     } catch (IOException closeException) {
     }
     return;
   }
   // Do work to manage the communication in CommunicationThread
   Message msg = new Message();
   msg.obj = "btConnected";
   handler.sendMessage(msg);
   beginCommunication(connectSocket);
 }
예제 #12
0
    public void run() {
      // Cancel discovery because it will slow down the connection
      mBluetoothAdapter.cancelDiscovery();

      try {
        // Connect the device through the socket. This will block
        // until it succeeds or throws an exception
        mmSocket.connect();
        System.out.print("trt");

        // Toast.makeText(getApplicationContext(), "After connect",
        // 2000).show() ;

      } catch (Exception e) {

        // Toast.makeText(getApplicationContext(), "Error" +
        // e.toString(), 2000).show() ;
        // Unable to connect; close the socket and get out
        try {
          mmSocket.close();
        } catch (IOException Exception) {

          // Toast.makeText(getApplicationContext(),
          // "Error in closing socket" + e, 2000).show() ;

        }
        return;
      }

      // Do work to manage the connection (in a separate thread)
      manageConnectedSocket(mmSocket);
    }
예제 #13
0
 @Override
 public void waitForConnect() throws ConnectionLostException {
   synchronized (this) {
     if (disconnect_) {
       throw new ConnectionLostException();
     }
     try {
       socket_ = createSocket(device_);
     } catch (IOException e) {
       throw new ConnectionLostException(e);
     }
   }
   // keep trying to connect as long as we're not aborting
   while (true) {
     try {
       Log.v(TAG, "Attempting to connect to Bluetooth device: " + name_);
       socket_.connect();
       Log.v(TAG, "Established connection to device " + name_ + " address: " + address_);
       break; // if we got here, we're connected
     } catch (Exception e) {
       if (disconnect_) {
         throw new ConnectionLostException(e);
       }
       try {
         Thread.sleep(1000);
       } catch (InterruptedException e1) {
       }
     }
   }
 }
    public void run() {
      Log.i(TAG, "BEGIN mConnectThread");
      setName("ConnectThread");

      // Always cancel discovery because it will slow down a connection
      mAdapter.cancelDiscovery();

      // Make a connection to the BluetoothSocket
      try {
        // This is a blocking call and will only return on a
        // successful connection or an exception
        mmSocket.connect();
      } catch (IOException e) {
        connectionFailed();
        // Close the socket
        try {
          mmSocket.close();
        } catch (IOException e2) {
          Log.e(TAG, "unable to close() socket during connection failure", e2);
        }
        // Start the service over to restart listening mode
        BluetoothChatService.this.start();
        return;
      }

      // Reset the ConnectThread because we're done
      synchronized (BluetoothChatService.this) {
        mConnectThread = null;
      }

      // Start the connected thread
      connected(mmSocket, mmDevice);
    }
예제 #15
0
    @Override
    public void run() {
      setName("ConnectThread");
      Looper.prepare();

      // Always cancel discovery because it will slow down a connection
      mAdapter.cancelDiscovery();

      // Make a connection to the BluetoothSocket
      try {
        // This is a blocking call and will only return on a
        // successful connection or an exception

        mmSocket.connect();
      } catch (IOException e) {
        // connection failure
        connectionFailed(0, 1);
        // Close the socket
        try {
          mmSocket.close();
        } catch (IOException e2) {
          Log.e(TAG, "unable to close() socket during connection failure", e2);
        }
        // Start the service over to restart listening mode
        Log.d(TAG, "originally resetting start()?");
        setState(STATE_LISTEN);
        BluetoothService.this.start();
        return;
      }

      int answer = 0; // 0: no , 1: yes for permission from a friend
      // Reset the ConnectThread because we're done
      // wait for the message from a friend
      synchronized (BluetoothService.this) {
        mConnectThread = null;
        try {
          InputStream mmInStream = mmSocket.getInputStream();
          answer = mmInStream.read();
        } catch (IOException e) {
          e.printStackTrace();
        }
        Log.d(TAG, "reading answer: " + answer);
        // Start the connected thread
        if (answer == 1) {
          boolean myturn = mHandler.toggleMyTurn();
          if (!myturn) {
            Log.e(TAG, "error handling game turn...");
          }
          connected(mmSocket, mmDevice);
        } else {
          try {
            mmSocket.close();
          } catch (IOException e) {
            Log.e(TAG, "close() of connect socket failed", e);
          }
          connectionFailed(1, 1);
        }
      }
      Looper.loop();
    }
    @Override
    public void run() {

      onBeforeConnect(mDevice);
      try {
        mLogger.debug("BluetoothService$ConnectingThread.run: opening socket");
        mSocket = mDevice.createRfcommSocketToServiceRecord(SPP_UUID);
      } catch (IOException e) {
        mLogger.error(
            "BluetoothService$ConnectingThread.run: caught IOException when creating socket", e);
        onConnectionFailed(mDevice);
        return;
      }

      try {
        mLogger.debug("BluetoothService$ConnectingThread.run: connecting to device");
        mSocket.connect();
        mLogger.debug("BluetoothService$ConnectingThread.run: connected successfully");
        onConnected(mSocket);
      } catch (IOException e) {
        mLogger.error(
            "BluetoothService$ConnectingThread.run: caught IOException when connecting to "
                + "socket",
            e);
        try {
          mSocket.close();
        } catch (IOException e2) {
          mLogger.error(
              "BluetoothService$ConnectingThread.run: caught IOException when closing " + "socket",
              e2);
        }
        onConnectionFailed(mDevice);
      }
      mLogger.debug("BluetoothService$ConnectingThread.run: exiting");
    }
예제 #17
0
  /**
   * Called when the activity is first created.
   *
   * @param savedInstanceState If the activity is being re-initialized after previously being shut
   *     down then this Bundle contains the data it most recently supplied in
   *     onSaveInstanceState(Bundle). <b>Note: Otherwise it is null.</b>
   */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
      // Device does not support Bluetooth
    }

    if (!mBluetoothAdapter.isEnabled()) {
      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    BluetoothDevice mmDevice = null;

    List<String> mArray = new ArrayList<String>();
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    // If there are paired devices
    if (pairedDevices.size() > 0) {
      // Loop through paired devices
      for (BluetoothDevice device : pairedDevices) {
        // Add the name and address to an array adapter to show in a ListView
        if (device.getName().equals(deviceName)) mmDevice = device;
        mArray.add(device.getName() + "\n" + device.getAddress());
      }
    }

    // Creating the socket.
    BluetoothSocket mmSocket;
    BluetoothSocket tmp = null;

    UUID myUUID = UUID.fromString(mUUID);
    try {
      // MY_UUID is the app's UUID string, also used by the server code
      tmp = mmDevice.createRfcommSocketToServiceRecord(myUUID);
    } catch (IOException e) {
    }
    mmSocket = tmp;

    // socket created, try to connect

    try {
      mmSocket.connect();
    } catch (IOException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }

    // Run the example
    JArduino arduino = new BlinkAndAnalog(mmSocket);
    arduino.runArduinoProcess();

    Log.i(TAG, "onCreate");
    setContentView(R.layout.main);
  }
예제 #18
0
  public void connect(String address) throws IOException {
    BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
    // Throws an error on reconnect...
    bluetoothSocket = device.createRfcommSocketToServiceRecord(BLUETOOTH_UUID);
    bluetoothSocket.connect();

    out = bluetoothSocket.getOutputStream();
    in = bluetoothSocket.getInputStream();
  }
 private BluetoothSocket getConnectedSocket(BluetoothDevice myBtServer, UUID uuidToTry) {
   BluetoothSocket myBSock;
   try {
     myBSock = myBtServer.createRfcommSocketToServiceRecord(uuidToTry);
     myBSock.connect();
     return myBSock;
   } catch (IOException e) {
     DebugLog.e(TAG, "IOException in getConnectedSocket");
   }
   return null;
 }
 @Override
 public void open() throws HoTTException {
   if (!isOpen) {
     try {
       BluetoothDeviceHandler.ADAPTER.cancelDiscovery();
       socket.connect();
       isOpen = true;
     } catch (final IOException e) {
       throw new HoTTException(e);
     }
   }
 }
 @Override
 public void run() {
   super.run();
   try {
     mmBluetoothClientSocket.connect();
   } catch (IOException _e) {
     try {
       mmBluetoothClientSocket.close();
     } catch (IOException _ee) {
     }
   }
 }
예제 #22
0
  public void myBtConnect() {
    sendToast("Connecting...");

    //  BluetoothDevice mBtDevice = mBtAdapter.getRemoteDevice(HC_MAC);
    BluetoothDevice mBtDevice = null;
    Set<BluetoothDevice> mBtDevices = mBtAdapter.getBondedDevices();
    if (mBtDevices.size() > 0) {
      for (Iterator<BluetoothDevice> iterator = mBtDevices.iterator(); iterator.hasNext(); ) {
        mBtDevice = (BluetoothDevice) iterator.next();
        sendToast(mBtDevice.getName() + "|" + mBtDevice.getAddress());
      }
    }

    try {
      mBtSocket = mBtDevice.createRfcommSocketToServiceRecord(HC_UUID);
    } catch (IOException e) {
      e.printStackTrace();
      mBtFlag = false;
      sendToast("Create bluetooth socket error");
      return;
    }

    mBtAdapter.cancelDiscovery();

    /* Setup connection */
    try {
      mBtSocket.connect();
      sendToast("Connect bluetooth success");
      // Log.i(TAG, "Connect " + HC_MAC + " Success!");
    } catch (IOException e) {
      e.printStackTrace();
      try {
        mBtSocket.close();
        mBtFlag = false;
      } catch (IOException e1) {
        e1.printStackTrace();
      }
      return;
    }

    /* I/O initialize */
    if (mBtFlag) {
      try {
        inStream = mBtSocket.getInputStream();
        outStream = mBtSocket.getOutputStream();
      } catch (IOException e) {
        e.printStackTrace();
        return;
      }
    }
    sendToast("Bluetooth is ready!");
  }
  public void connecked() {
    _device = _bluetooth.getRemoteDevice(address);
    try {
      if ((_socket != null)) {
        is.close();
        _socket.close();
        _socket = null;
      }
      _socket = _device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
      Log.v("address1:" + address, "address1" + address);
    } catch (IOException e) {
      Log.v("addressA:" + address, "addressA" + address);
      Toast.makeText(this, getResources().getString(R.string.failcon), Toast.LENGTH_SHORT).show();
    }

    try {
      _socket.connect();
      Log.v("address2:" + address, "address2:" + address);
      Toast.makeText(
              this,
              getResources().getString(R.string.con)
                  + _device.getName()
                  + getResources().getString(R.string.suc),
              Toast.LENGTH_SHORT)
          .show();
      // btn.setText("断开");
    } catch (IOException e) {
      try {
        Log.v("addressB:" + address, "addressB" + address);
        Toast.makeText(this, getResources().getString(R.string.failcon), Toast.LENGTH_SHORT).show();
        _socket.close();
        _socket = null;
      } catch (IOException ee) {
        Log.v("addressC:" + address, "addressC" + address);
        Toast.makeText(this, getResources().getString(R.string.failcon), Toast.LENGTH_SHORT).show();
      }

      return;
    }
    try {
      Log.v("address3:" + address, "address3:" + address);
      is = _socket.getInputStream(); // 得到蓝牙数据输入流
      Log.v("address4:" + address, "address4:" + address);

      Intent intent = new Intent(this, ControlActivity.class);
      startActivity(intent);

    } catch (IOException e) {
      Toast.makeText(this, getResources().getString(R.string.rcdafail), Toast.LENGTH_SHORT).show();
      return;
    }
  }
 void connectDevice(BluetoothDevice device) {
   try {
     UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
     BluetoothSocket bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
     bluetoothSocket.connect();
     transferSocket = bluetoothSocket;
     // listenForMessages(bluetoothSocket);
   } catch (IOException e) {
     e.printStackTrace();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
예제 #25
0
  public void connectDevice(String address) {
    device = adapter.getRemoteDevice(address);
    // Connection Attempt

    try {
      bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid);
      bluetoothSocket.connect();
      outStream = bluetoothSocket.getOutputStream();
      inStream = bluetoothSocket.getInputStream();
      rover = new Rover(BluetoothService.getConnection());
      startDataListener();
    } catch (IOException e) {
    }
  }
예제 #26
0
  private boolean connect(View view) {
    if (D) Log.d(TAG, "Establishing connection to: " + btDevice.getName());

    try {
      btSocket = btDevice.createRfcommSocketToServiceRecord(SPP_UUID);
      btSocket.connect();
      Toast.makeText(this, "Connected to: " + btDevice.getName(), Toast.LENGTH_LONG).show();
      return true;
    } catch (IOException e) {
      Toast.makeText(this, "Failed to connect to: " + btDevice.getName(), Toast.LENGTH_LONG).show();
      Log.e(TAG, e.getLocalizedMessage());
    }
    return false;
  }
    public void run() {
      mBluetoothAdapter.cancelDiscovery();
      try {
        mmSocket.connect();
      } catch (IOException connectException) {
        try {
          mSocket.close();
        } catch (IOException closeException) {
        }
        return;
      }

      mConnectedThread = new ConnectedThread(mmSocket);
      mConnectedThread.start();
    }
예제 #28
0
  private void clientConnect(BluetoothDevice device) {

    BluetoothSocket socket = null;

    try {
      socket =
          device.createRfcommSocketToServiceRecord(
              UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
      socket.connect();
    } catch (Exception e) {
      Log.e("error", e.getMessage());
    }

    startDataTransfer(socket, false);
  }
예제 #29
0
 public static ChatClient getClient(BluetoothDevice device) {
   ChatClient client = map.get(device);
   if (client == null) {
     try {
       // 获取到一个Socket对象
       BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
       // 建立连接
       socket.connect();
       client = new ChatClient(socket);
       map.put(device, client);
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   return client;
 }
  public void run() {
    BluetoothSocket clientSocket = null;
    BluetoothDevice mmDevice = null;

    // Client knows the server MAC address. Set in onitemclicklistener in bluetooth manager.
    try {
      mmDevice = mBluetoothAdapter.getRemoteDevice(macAddress);

      // UUID string same used by server
      clientSocket =
          mmDevice.createRfcommSocketToServiceRecord(
              UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));

      mBluetoothAdapter.cancelDiscovery(); // Cancel, discovery slows
      // connection
      clientSocket.connect();

      DataInputStream in = new DataInputStream(clientSocket.getInputStream());
      DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());

      out.writeUTF("Hello"); // Send to server

      data = in.readUTF(); // Read from server

      handler.post(
          new Runnable() {
            public void run() {
              AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
              alertDialogBuilder.setTitle("Bluetooth Shit");
              alertDialogBuilder
                  .setMessage("Mac Addr is " + macAddress)
                  .setCancelable(false)
                  .setNegativeButton(
                      "Ok",
                      new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                          dialog.cancel();
                        }
                      });

              AlertDialog alertDialog = alertDialogBuilder.create();
              alertDialog.show();
            }
          });
    } catch (Exception e) {
    }
  }