Пример #1
1
        public void run() {
          BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
          UUID uuid = UUID.fromString("4e5d48e0-75df-11e3-981f-0800200c9a66");
          try {
            BluetoothServerSocket serverSocket =
                adapter.listenUsingRfcommWithServiceRecord("BLTServer", uuid);
            android.util.Log.e("TrackingFlow", "Listening...");

            // Connection accepted and opening
            socket = serverSocket.accept();
            android.util.Log.e("TrackingFlow", "Socket accepted...");

            // Setup input and output streams
            is = socket.getInputStream();
            os = new OutputStreamWriter(socket.getOutputStream());

            // Enable the setup and learning buttons now
            runOnUiThread(enableButtons);

            // Store the socket for future use
            ((TEDTablet) getApplication()).setSocket(socket);

          } catch (IOException e) {
            e.printStackTrace();
          }
        }
    public void run() {
      BluetoothSocket bluetoothSocket;
      while (true) {
        try {
          bluetoothSocket = bluetoothServerSocket.accept();
        } catch (IOException e) {
          break;
        }
        if (bluetoothSocket != null) {

          runOnUiThread(
              new Runnable() {
                public void run() {
                  Toast.makeText(
                          getApplicationContext(),
                          "A connection has been accepted.",
                          Toast.LENGTH_SHORT)
                      .show();
                }
              });

          connected(bluetoothSocket, bluetoothSocket.getRemoteDevice());

          try {
            bluetoothServerSocket.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
          break;
        }
      }
    }
  public void sendMessage(String destination, String message) {
    try {
      BluetoothSocket myBsock = btSockets.get(destination);
      if (myBsock != null) {
        OutputStream outStream = myBsock.getOutputStream();
        byte[] stringAsBytes = (message + " ").getBytes();
        stringAsBytes[stringAsBytes.length - 1] = 0; // Add a stop marker
        outStream.write(stringAsBytes);
        DebugLog.i(TAG, "successful sendMessage - Dest:" + destination + ", Msg:" + message);
        Message msg = mHandler.obtainMessage(DynamicAppBluetooth.MESSAGE_WRITE);
        Bundle bundle = new Bundle();
        bundle.putBoolean(DynamicAppBluetooth.SEND_RESULT, true);
        msg.setData(bundle);
        mHandler.sendMessage(msg);
      } else {
        Message msg = mHandler.obtainMessage(DynamicAppBluetooth.MESSAGE_WRITE);
        Bundle bundle = new Bundle();
        bundle.putBoolean(DynamicAppBluetooth.SEND_RESULT, false);
        msg.setData(bundle);
        mHandler.sendMessage(msg);
      }
    } catch (IOException e) {
      DebugLog.e(TAG, "IOException in sendMessage - Dest:" + destination + ", Msg:" + message);
      Message msg = mHandler.obtainMessage(DynamicAppBluetooth.MESSAGE_WRITE);
      Bundle bundle = new Bundle();
      bundle.putBoolean(DynamicAppBluetooth.SEND_RESULT, false);
      msg.setData(bundle);
      mHandler.sendMessage(msg);
    }

    return;
  }
  public synchronized void disconnect(BluetoothDevice device) {
    String addressToStop = device.getAddress();
    BluetoothSocket socket = btSockets.get(addressToStop);
    if (socket != null) {
      try {
        socket.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    btSockets.remove(addressToStop);
    btDeviceAddresses.remove(addressToStop);

    DebugLog.i(TAG, "stop");

    int size = connectedThreads.size();

    for (int i = 0; i < size; i++) {
      ConnectedThread conThread = connectedThreads.get(i);

      if (conThread != null) {
        String address = conThread.getMmDevice().getAddress();
        if (addressToStop.equals(address)) {
          conThread = null;
          connectedThreads.remove(i);
          break;
        }
      }
    }

    this.start();
  }
Пример #5
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);
      }
    }
Пример #6
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);
 }
Пример #7
0
  public void run() {
    while (ready == true) {

      int s;
      try {
        s = socket.getInputStream().read();

        while (s != -1) {
          if (s == 13) {
            Log.v("BluetoothThread", "received message: " + buffer);
            synchronized (parent) {
              parent.received(buffer);
            }
            buffer = "";
            s = (char) socket.getInputStream().read();
          } else {
            buffer += (char) s;
            Log.v("BluetoothThread", "received : " + s);
            s = (char) socket.getInputStream().read();
          }
        }
      } catch (IOException e) {
        Log.v("BluetoothThread", "IO Exception on receive");
        // alert the parent class
        // wait for reconnect
        ready = false;
        parent.received("DISCONNECT");
      }

      if (timeSinceLastDiscovery + 12000 < System.currentTimeMillis()) {
        timeSinceLastDiscovery = System.currentTimeMillis();
      }
    }
  }
Пример #8
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);
    }
Пример #9
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() {
      setName(mHostName);

      // establish the server socket
      try {
        mLogger.debug("BluetoothService$ListeningThread.run: opening server socket");
        mServerSocket = mBtAdapter.listenUsingRfcommWithServiceRecord(mHostName, mHostUUID);
      } catch (IOException e) {
        mLogger.error(
            "BluetoothService$ListeningThread.run: caught IOException from "
                + "listenUsingRfcommWithServiceRecord() call",
            e);
        return;
      }

      BluetoothSocket socket = null;

      while (getServiceState() == BluetoothService.State.STATE_LISTENING) {
        try {
          // listen on the server socket.  Keep in mind that the state can change while we're
          // waiting.
          // Note that when this call returns a BluetoothSocket, the socket is _already_ connected.
          mLogger.debug("BluetoothService$ListeningThread.run: calling accept()");
          socket = mServerSocket.accept(); // blocking call

          mLogger.debug(
              "BluetoothService$ListeningThread.run: accepted remote connection, "
                  + "current state = "
                  + getServiceState().toString());

          onInboundConnectionRequestReceived(socket.getRemoteDevice());
        } catch (IOException e) {
          mLogger.error(
              "BluetoothService$ListeningThread.run: caught IOException from server socket "
                  + "accept() call",
              e);
          break;
        }

        if (getServiceState() == BluetoothService.State.STATE_LISTENING) {
          onInboundConnection(socket);
        } else {
          mLogger.debug(
              "BluetoothService$ListeningThread.run: current state is not "
                  + "STATE_LISTENING, so closing socket");
          try {
            socket.close();
          } catch (IOException e) {
            mLogger.error(
                "BluetoothService$ListeningThread.run: caught IOException from "
                    + "socket close() call",
                e);
            break;
          }
        }
      }
      mLogger.debug("BluetoothService$ListeningThread.run: exiting");
      cancel();
    }
  public ConnectedThread(BluetoothSocket socket, BFVService service) {

    this.service = service;

    Log.d(BFVService.TAG, "create ConnectedThread");
    mmSocket = socket;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;
    BufferedReader tmpReader = null;

    // Get the BluetoothSocket input and output streams
    try {
      tmpIn = socket.getInputStream();
      tmpOut = socket.getOutputStream();
      tmpReader = new BufferedReader(new InputStreamReader(tmpIn), 256);
    } catch (IOException e) {
      Log.e(BFVService.TAG, "temp sockets not created", e);
    }

    mmOutStream = tmpOut;
    mmReader = tmpReader;

    chargeFromVolts = new PiecewiseLinearFunction(new Point2d(3.6, 0.0));
    chargeFromVolts.addNewPoint(new Point2d(3.682, 0.032));
    chargeFromVolts.addNewPoint(new Point2d(3.696, 0.124));
    chargeFromVolts.addNewPoint(new Point2d(3.75, 0.212));
    chargeFromVolts.addNewPoint(new Point2d(3.875, 0.624));
    chargeFromVolts.addNewPoint(new Point2d(3.96, 0.73));
    chargeFromVolts.addNewPoint(new Point2d(4.16, 1.0));

    firstPressure = false;
  }
Пример #12
0
    public void run() {
      BluetoothSocket socket = null;
      // Keep listening until exception occurs or a socket is returned
      while (true) {
        try {

          socket = serverSocket.accept();
          dHandler
              .obtainMessage(
                  SocioPhoneConstants.BT_ACCEPT, "Accept " + socket.getRemoteDevice().getName())
              .sendToTarget();
          sHandler.obtainMessage(SocioPhoneConstants.BT_ACCEPT, servers.size() + "").sendToTarget();
          ServerThread server = new ServerThread(socket, sHandler, dHandler, device_list);
          server.start();
          servers.add(server);

          // TODO : Change below thing...

          // Send a time-sync packet to client
          server.SendData("/5:" + System.currentTimeMillis());

        } catch (IOException e) {
          dHandler.obtainMessage(SocioPhoneConstants.BT_EXCEPTION, e.getMessage()).sendToTarget();
          break;
        }
        // If the connection is accepted
        if (socket != null) {
          // Do work to manage the connection (in a separate thread)
          client_sockets.add(socket);
        }
      }
    }
  @Override
  public void disconnect(BtDevice btDevice) {
    BtContainer btContainer = AppProvider.getBtContainer();

    BluetoothSocket socket = btContainer.getSocketForDevice(btDevice);
    if (socket != null) {
      try {
        InputStream is = socket.getInputStream();

        OutputStream os = socket.getOutputStream();

        if (is != null) {
          is.close();
        }

        if (os != null) {
          os.close();
        }

        socket.close();
      } catch (IOException e) {
        btControllerInterface.disconnectFailed(btDevice);
      }
    }

    btContainer.removeConnected(btDevice);
    btControllerInterface.updateConnectedList();
  }
    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);
    }
Пример #15
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();
      }
    }
 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());
     }
   }
 }
    @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");
    }
Пример #18
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();
    }
Пример #19
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");
    }
    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);
    }
  public void makeconnection() {

    try {
      in = mysocket.getInputStream();
      out = mysocket.getOutputStream();

      oos = new ObjectOutputStream(out);
      // oos = new ObjectOutputStream(new BufferedOutputStream(out));
      oos.flush();

      ois = new ObjectInputStream(in);
      // ois =new ObjectInputStream(new BufferedInputStream(in));

      System.out.println("connection established");

      waitforreceivingdata();

    } catch (SocketException ex) {
      Log.d(TAG, "Hubo error makeconnection 1");

    } catch (IOException ex) {
      Log.d(TAG, "Hubo error makeconnection 2");
    } catch (Exception ex) {
      Log.d(TAG, "Hubo error makeconnection 3");
    }
  }
Пример #22
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);
    }
    /**
     * Listens for any incoming bluetooth connections and attempts to start the connection process
     * if a connection is requested.
     *
     * @see com.example.drawfriends.BluetoothService#connected(BluetoothSocket, BluetoothDevice)
     */
    public void run() {
      setName("AcceptThread");
      BluetoothSocket socket = null;
      // Listen to the server socket if we're not connected
      while (mState != STATE_CONNECTED) {
        try {
          // This is a blocking call and will only return on a
          // successful connection or an exception
          socket = mmServerSocket.accept();
        } catch (IOException e) {
          break;
        }

        // If a connection was accepted
        if (socket != null) {
          synchronized (BluetoothService.this) {
            switch (mState) {
              case STATE_LISTEN:
              case STATE_CONNECTING:
                // Situation normal. Start the connected thread.
                connected(socket, socket.getRemoteDevice());
                break;
              case STATE_NONE:
              case STATE_CONNECTED:
                // Either not ready or already connected. Terminate new socket.
                try {
                  socket.close();
                } catch (IOException e) {
                }
                break;
            }
          }
        }
      }
    }
Пример #24
0
    public void run() {
      if (D) Log.d(TAG, "BEGIN accept Thread" + this);
      setName("AcceptThread");
      BluetoothSocket socket = null;

      // Listen to the server socket if we're not connected
      while (mState != STATE_CONNECTED) {
        try {
          // This is a blocking call and will only return on a
          // successful connection or an exception
          if (D) Log.d(TAG, "try accept");
          socket = mmServerSocket.accept(); // time block here

          if (D) Log.d(TAG, "after try accept:" + socket.toString());
        } catch (IOException e) {
          Log.e(TAG, "accept() failed", e);
          break;
        }

        // If a connection was accepted
        if (socket != null) {
          if (D) Log.d(TAG, "Socket ! null" + mState);
          synchronized (BluetoothService.this) {
            switch (mState) {
              case STATE_LISTEN:
              case STATE_CONNECTING:
                // Situation normal. Start the connected thread.
                if (D) Log.d(TAG, "connected");

                connected(socket, socket.getRemoteDevice());
                /*
                try{
                	mmServerSocket.close();
                	if (D) Log.d(TAG, "ServerSocket Closed" + mState);
                	mHandler.obtainMessage(KY202Monitor.MESSAGE_SERVERSOCKET_CLOSE, 1, -1).sendToTarget();

                }catch(IOException e) {
                //BTServiceStart(mBTService);
                	Log.e(TAG, "Could not close ServerSocket", e);
                }
                */
                break;
              case STATE_NONE:
              case STATE_CONNECTED:
                // Either not ready or already connected. Terminate new socket.
                try {
                  socket.close();
                } catch (IOException e) {
                  Log.e(TAG, "Could not close unwanted socket", e);
                }
                break;
            }
          }
        }
      }
      // if (D) //Log.i(TAG, "END mAcceptThread");
    }
Пример #25
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();
  }
Пример #26
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);
  }
Пример #27
0
  public ConnectedThread(BluetoothSocket socket, ConnectedThreadListener listener)
      throws IOException {
    this.socket = socket;
    this.listener = listener;
    this.remoteDevice = socket.getRemoteDevice();

    objOutput = new ObjectOutputStream(socket.getOutputStream());
    objOutput.flush();
    objInput = new ObjectInputStream(socket.getInputStream());
  }
  /**
   * 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);
  }
 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;
 }
 /** Finaliza o socket Bluetooth e encerra todas as conexões */
 private synchronized void closeBluetoothConnection() {
   BluetoothSocket socket = mBluetoothSocket;
   mBluetoothSocket = null;
   if (socket != null) {
     try {
       Thread.sleep(50);
       socket.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }