示例#1
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();
    }
示例#2
0
 public static BluetoothSocket createSocket(final BluetoothDevice device) throws IOException {
   if (Build.VERSION.SDK_INT >= 10) {
     // We're trying to create an insecure socket, which is only
     // supported in API 10 and up. Otherwise, we try a secure socket
     // which is in API 7 and up.
     return device.createInsecureRfcommSocketToServiceRecord(
         UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
   } else {
     return device.createRfcommSocketToServiceRecord(
         UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
   }
 }
 private static BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
   if (Build.VERSION.SDK_INT >= 10) {
     try {
       final Method m =
           device
               .getClass()
               .getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] {UUID.class});
       return (BluetoothSocket) m.invoke(device, MY_UUID);
     } catch (Exception e) {
     }
   }
   return device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
 }
 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();
   }
 }
    public ConnectThread(BluetoothDevice device, boolean secure) {
      mmDevice = device;
      BluetoothSocket tmp = null;
      mSocketType = "Insecure";

      // Get a BluetoothSocket for a connection with the
      // given BluetoothDevice
      try {
        tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
      } catch (IOException e) {
        Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
      }
      mmSocket = tmp;
    }
 @TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
 @Override
 protected Void doInBackground(
     Void... devices) // while the progress dialog is shown, the connection is done in background
     {
   try {
     if (btSocket == null || !isBtConnected) {
       myBluetooth = BluetoothAdapter.getDefaultAdapter(); // get the mobile bluetooth device
       BluetoothDevice dispositivo =
           myBluetooth.getRemoteDevice(
               address); // connects to the device's address and checks if it's available
       btSocket =
           dispositivo.createInsecureRfcommSocketToServiceRecord(
               myUUID); // create a RFCOMM (SPP) connection
       BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
       btSocket.connect(); // start connection
     }
   } catch (IOException e) {
     ConnectSuccess = false; // if the try failed, you can check the exception here
   }
   return null;
 }
    public ConnectThread(BluetoothDevice device, boolean secure) {
      if (DEBUG) {
        Log.d(TAG, "ConnectThread constructor");
      }

      mmDevice = device;
      BluetoothSocket tmp = null;
      mSocketType = secure ? "Secure" : "Insecure";

      // Get a BluetoothSocket for a connection with the
      // given BluetoothDevice
      try {
        if (secure) {
          tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
        } else {
          tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
        }
      } catch (IOException e) {
        if (DEBUG) {
          Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
        }
      }
      mmSocket = tmp;
    }
    @Override
    public void run() {

      timestamp = System.currentTimeMillis();

      if (Constants.USE_TCP_DEBUG) {
        /* Use TCP socket to connect */
        Socket s = new Socket();

        // Try to connect for 50 seconds
        int result = 0;
        for (int i = 0; i < CONNECT_RETRY_TIME && result == 0; i++) {
          try {
            s.connect(new InetSocketAddress(host, channel), CONNECT_WAIT_TIMEOUT);
          } catch (UnknownHostException e) {
            Log.e(TAG, "TCP socket connect unknown host ");
          } catch (IOException e) {
            Log.e(TAG, "TCP socket connect failed ");
          }
          if (s.isConnected()) {
            if (D) Log.d(TAG, "TCP socket connected ");
            isConnected = true;
            break;
          }
          if (isInterrupted()) {
            Log.e(TAG, "TCP socket connect interrupted ");
            markConnectionFailed(s);
            return;
          }
        }
        if (!isConnected) {
          Log.e(TAG, "TCP socket connect failed after 20 seconds");
          markConnectionFailed(s);
          return;
        }

        if (V)
          Log.v(
              TAG,
              "TCP Socket connection attempt took "
                  + (System.currentTimeMillis() - timestamp)
                  + " ms");

        TestTcpTransport transport;
        transport = new TestTcpTransport(s);

        if (isInterrupted()) {
          isConnected = false;
          markConnectionFailed(s);
          transport = null;
          return;
        }
        if (!isConnected) {
          transport = null;
          Log.e(TAG, "TCP connect session error: ");
          markConnectionFailed(s);
          return;
        } else {
          if (D) Log.d(TAG, "Send transport message " + transport.toString());
          mSessionHandler.obtainMessage(RFCOMM_CONNECTED, transport).sendToTarget();
        }
      } else {

        /* Use BluetoothSocket to connect */

        try {
          btSocket =
              device.createInsecureRfcommSocketToServiceRecord(
                  BluetoothUuid.ObexObjectPush.getUuid());
        } catch (IOException e1) {
          Log.e(TAG, "Rfcomm socket create error", e1);
          markConnectionFailed(btSocket);
          return;
        }
        try {
          btSocket.connect();

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

          BluetoothOppPreference.getInstance(mContext).setName(device, device.getName());

          if (V) Log.v(TAG, "Send transport message " + transport.toString());

          mSessionHandler.obtainMessage(RFCOMM_CONNECTED, transport).sendToTarget();
        } catch (IOException e) {
          Log.e(TAG, "Rfcomm socket connect exception", e);
          // If the devices were paired before, but unpaired on the
          // remote end, it will return an error for the auth request
          // for the socket connection. Link keys will get exchanged
          // again, but we need to retry. There is no good way to
          // inform this socket asking it to retry apart from a blind
          // delayed retry.
          if (!mRetry && e.getMessage().equals(SOCKET_LINK_KEY_ERROR)) {
            Message msg = mSessionHandler.obtainMessage(SOCKET_ERROR_RETRY, -1, -1, device);
            mSessionHandler.sendMessageDelayed(msg, 1500);
          } else {
            markConnectionFailed(btSocket);
          }
        }
      }
    }
  @TargetApi(10)
  void connect(Context context) {

    try {

      MetaWatchService.fakeWatch = false;
      if (Preferences.watchMacAddress.equals("DIGITAL")) {
        MetaWatchService.fakeWatch = true;
        MetaWatchService.watchType = MetaWatchService.WatchType.DIGITAL;
      }
      if (Preferences.watchMacAddress.equals("ANALOG")) {
        MetaWatchService.fakeWatch = true;
        MetaWatchService.watchType = MetaWatchService.WatchType.ANALOG;
      }

      if (Preferences.logging)
        Log.d(MetaWatch.TAG, "Remote device address: " + Preferences.watchMacAddress);
      if (!Preferences.loaded) loadPreferences(context);

      if (!MetaWatchService.fakeWatch) {

        if (bluetoothAdapter == null) {
          sendToast(getResources().getString(R.string.error_bluetooth_not_supported));
          return;
        } else if (!bluetoothAdapter.isEnabled()) {
          sendToast(getResources().getString(R.string.error_bluetooth_not_enabled));
          return;
        }

        wakeLock.acquire(5000);

        BluetoothDevice bluetoothDevice =
            bluetoothAdapter.getRemoteDevice(Preferences.watchMacAddress);

        if (Preferences.skipSDP) {
          Method method =
              bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
          bluetoothSocket = (BluetoothSocket) method.invoke(bluetoothDevice, 1);
        } else {
          UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

          int currentapiVersion = android.os.Build.VERSION.SDK_INT;

          if (Preferences.insecureBtSocket
              && currentapiVersion >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
            bluetoothSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid);
          } else {
            bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
          }
        }

        bluetoothAdapter.cancelDiscovery();
        bluetoothSocket.connect();

        inputStream = bluetoothSocket.getInputStream();
        outputStream = bluetoothSocket.getOutputStream();
      }

      connectionState = ConnectionState.CONNECTED;
      updateNotification();

      Protocol.startProtocolSender();

      // RM: This is disabled for now, as it seems to confuse the watch fw (3.1.0S tested)
      // and get it into a state where it won't accept any date/time format updates :-S

      // if( Preferences.autoClockFormat )
      //	Protocol.setTimeDateFormat(this);

      Protocol.getRealTimeClock();
      Protocol.getDeviceType();

      Notification.startNotificationSender(this);

      Idle.updateIdle(this, true);

    } catch (IOException ioexception) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, ioexception.toString());
    } catch (SecurityException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } catch (NoSuchMethodException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } catch (IllegalArgumentException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } catch (IllegalAccessException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } catch (InvocationTargetException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } catch (NullPointerException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } finally {
      if (wakeLock != null && wakeLock.isHeld()) {
        wakeLock.release();
      }
    }

    return;
  }
示例#10
0
  @Override
  public byte[] getByteArray(String locator, String hash) {

    byte[] data = new byte[3000000];
    int connectAttemptsCounter = 0;

    if (locator.contains(NIMACBT)) {
      if (D) Log.d(TAG, " Connection process   - Starting connection process!");
      String mac = getMacAddressFromLocator(locator);
      BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mac);

      BluetoothSocket mmSocket = null;
      BluetoothSocket tmp = null;

      try {
        tmp = device.createInsecureRfcommSocketToServiceRecord(BO_TRANSFER_UUID);
      } catch (IOException e) {
        if (D) Log.e(TAG, "create() failed - (createInsecureRfcommSocketToServiceRecord) ", e);
      }
      mmSocket = tmp;

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

      while (connectAttemptsCounter < retryAttempts) {

        connectAttemptsCounter++;
        // 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();
          if (D) Log.d(TAG, " Connection process   - Connection established - Socket connected");
          if (D) Log.d(TAG, " Transferring Process - Starting file transfer");
          data = getByteArrayFromRemotePeer(mmSocket, hash);
          if (data != null) {
            if (D) Log.d(TAG, " Transferring Process - File transferring done!");
            return data;
          }

        } catch (IOException e) {
          if (D)
            Log.e(
                TAG,
                "failure while connecting to the socket - (createInsecureRfcommSocketToServiceRecord) ",
                e);
        } finally {
          try {
            if (mmSocket.isConnected()) {
              mmSocket.close();
            }
          } catch (IOException e2) {
            Log.e(TAG, "unable to close()  socket during connection failure", e2);
          }
        }
      }
      return null;
    }
    return null;
  }
  @Override
  public void run() {
    handler.obtainMessage(MESSAGE_DEVICE_NAME_CHANGE, 0, 0, getDeviceName());

    Throwable error = null;
    try {
      socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
      setState(State.CONNECTING, null);
      socket.connect();
      setState(State.CONNECTED, null);

      InputStream in = socket.getInputStream();
      StringBuilder message = new StringBuilder();
      byte[] buffer = new byte[512];
      while (running.get()) {
        int bytesRead = in.read(buffer);
        // ISO-8859-1 contains all 256 bytes
        message.append(new String(buffer, 0, bytesRead, "ISO-8859-1"));

        int end;
        while ((end = message.indexOf("\n")) != -1) {
          handler.obtainMessage(MESSAGE_READ, bytesRead, 0, message.toString()).sendToTarget();
          message.delete(0, end + 1);
        }
      }

      setState(State.CLOSING, null);
    } catch (IOException e) {
      error = e;
    } finally {
      try {
        // Synchronized prevents "ABORTING: INVALID HEAP ADDRESS IN dlfree" in android 4.0.4
        synchronized (this) {
          socket.close();
        }
        if (closedExplicitly.get()) setState(State.CLOSED, null);
        else setState(State.ERROR, error);
      } catch (IOException e) {
        setState(State.ERROR, error == null ? e : error);
      }
    }
  }