Ejemplo n.º 1
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();
    }
  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;
    }
  }
    @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");
    }
Ejemplo n.º 4
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);
 }
Ejemplo n.º 5
0
 public void cancel() {
   try {
     mmSocket.close();
   } catch (IOException e) {
     TopoDroidLog.Log(TopoDroidLog.LOG_ERR, "close() of connect socket failed " + e);
   }
 }
Ejemplo n.º 6
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() {

      // 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);
    }
 @Override
 public void close() throws IOException {
   if (isOpen) {
     socket.close();
     isOpen = false;
   }
 }
Ejemplo n.º 9
0
  @Override
  public void disconnect() {

    if (!this.isConnected()) {
      return;
    }

    if (inputStream != null) {
      try {
        inputStream.close();
      } catch (Exception e) {
      }
      inputStream = null;
    }

    if (outputStream != null) {
      try {
        outputStream.close();
      } catch (Exception e) {
      }
      outputStream = null;
    }

    if (btSocket != null) {
      try {
        btSocket.close();
      } catch (Exception e) {
      }
      btSocket = null;
    }

    if (disconnectCallback != null) {
      disconnectCallback.disconnect();
    }
  }
 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());
     }
   }
 }
Ejemplo n.º 11
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);
    }
Ejemplo n.º 12
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);
      }
    }
 // Cancel an open connection and terminate the thread
 public void cancel() {
   try {
     bluetoothSocket.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  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();
  }
Ejemplo n.º 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();
      }
    }
Ejemplo n.º 16
0
 public void cancelar() {
   try {
     socketConectado.close();
   } catch (IOException e) {
     Log.e(TAG, "close() of connect socket failed", e);
   }
 }
Ejemplo n.º 17
0
 public void cancel() {
   try {
     mySocket.close();
   } catch (IOException e) {
     Log.e("Bluetooth", mDevice.getName() + ": Could not close socket");
   }
 }
    public void close() {
      if (mInputStream != null) {
        try {
          mInputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (mOutputStream != null) {
        try {
          mOutputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      if (mBluetoothSocket != null) {
        try {
          mBluetoothSocket.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      if (mBluetoothServerSocket != null) {
        try {
          mBluetoothServerSocket.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    /**
     * 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;
            }
          }
        }
      }
    }
Ejemplo n.º 20
0
  public void disconnect() {
    if (mDeviceSocket != null) {
      try {
        mDeviceSocket.close();
        mDeviceSocket = null;
      } catch (IOException e) {
        Logger.BT("ERROR: close socket failed (" + e.getMessage() + ")");
      }
    }
    if (mOutputStream != null) {
      try {
        mOutputStream.close();
        mOutputStream = null;
      } catch (IOException e) {
        Logger.BT("ERROR: close output stream failed (" + e.getMessage() + ")");
      }
    }
    if (mInputStream != null) {
      try {
        mInputStream.close();
        mInputStream = null;
      } catch (IOException e) {
        Logger.BT("ERROR: close input stream failed (" + e.getMessage() + ")");
      }
    }

    mSelectedDevice = null;
    isConnected = false;
  }
Ejemplo n.º 21
0
  public void destroy() {
    // Added in 6/11/2015
    if (isServer) {
      sendToClients("/1024:0");
      isServer = false;
    }
    if (wifiMode) {
      tcpManager.destroy();
    } else {
      try {
        if (mSocket != null) {
          mSocket.close();
        }
        if (serverSocket != null) {
          serverSocket.close();
        }
        if (client_sockets != null) {
          Iterator<BluetoothSocket> iter = client_sockets.iterator();
          while (iter.hasNext()) iter.next().close();

          client_sockets.clear();
        }
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        dHandler.obtainMessage(SocioPhoneConstants.BT_EXCEPTION, e.getMessage()).sendToTarget();
      }
    }
  }
Ejemplo n.º 22
0
 // Cancel an in-progress connection and close the socket
 public void cancel() {
   Log.w(TAG, "ConnectionThread - cancel()");
   try {
     connectSocket.close();
   } catch (IOException e) {
   }
 }
 public void cancel() {
   try {
     mmSocket.close();
   } catch (IOException e) {
     Log.e(TAG, "close() of connect socket failed", e);
   }
 }
    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);
    }
    @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();
    }
Ejemplo n.º 26
0
 public void cerraSocket() {
   try {
     mmSocket.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 27
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);
    }
  @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();
  }
Ejemplo n.º 29
0
 /* Call this from the main Activity to shutdown the connection */
 public void cancel() {
   stopThread = true;
   try {
     mmSocket.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 30
0
 /* matikan connection */
 public void cancel() {
   try {
     mmSocket.close();
   } catch (IOException e) {
     Log.e("ywlog", e.getMessage());
     e.printStackTrace();
   }
 }