/**
   * Start the chat service. Specifically start AcceptThread to begin a session in listening
   * (server) mode. Called by the Activity onResume()
   */
  public synchronized void start() {
    Log.d(TAG, "start");

    // Cancel any thread attempting to make a connection
    if (mConnectThread != null) {
      mConnectThread.cancel();
      mConnectThread = null;
    }

    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {
      mConnectedThread.cancel();
      mConnectedThread = null;
    }

    setState(STATE_LISTEN);

    // Start the thread to listen on a BluetoothServerSocket
    if (mSecureAcceptThread == null) {
      mSecureAcceptThread = new AcceptThread(true);
      mSecureAcceptThread.start();
    }
    if (mInsecureAcceptThread == null) {
      mInsecureAcceptThread = new AcceptThread(false);
      mInsecureAcceptThread.start();
    }
  }
  /** Stop all threads */
  public synchronized void stop() {
    if (DEBUG) {
      Log.i(TAG, "Synchronized stop()");
    }

    if (mConnectThread != null) {
      mConnectThread.closeSocket();
      mConnectThread = null;
    }

    if (mConnectedThread != null) {
      mConnectedThread.closeSocket();
      mConnectedThread = null;
    }

    if (mSecureAcceptThread != null) {
      mSecureAcceptThread.closeSocket();
      mSecureAcceptThread = null;
    }

    if (mInsecureAcceptThread != null) {
      mInsecureAcceptThread.closeSocket();
      mInsecureAcceptThread = null;
    }
    setState(STATE_NONE);
  }
 public void openServer() {
   // Added in 6/11/2015
   isServer = true;
   if (wifiMode) {
     tcpManager.serverStart();
   } else {
     Log.i("MYTAG", "Accept thread start");
     AcceptThread accept = new AcceptThread();
     accept.start();
   }
 }
Example #4
0
  /**
  * 启动服务端线程
  */
 public synchronized void start(){
 	//TODO 这个还没有试验
 	if(mAcceptThread!=null){
 		mAcceptThread.cancel();
 		mAcceptThread = null;
 	}
 	 mAcceptThread = new AcceptThread();
 	 mAcceptThread.start();
 	 
 	/*if(mConnectThread!=null){
 		mConnectThread.cancle();
 	}*/
 	
  }
Example #5
0
  /** 设备列表的单击响应函数,点击列表项,开始与该蓝牙设备建立连接 */
  @SuppressLint("HandlerLeak")
  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    DeviceList remoteDeviceList = deviceList.getItem(position);
    deviceName = remoteDeviceList.getRemoteDeviceName();

    bluetoothAdapter.cancelDiscovery(); // 停止查找设备
    AcceptThread aThread = new AcceptThread(bluetoothAdapter, serverName, MY_UUID);
    aThread.start(); // 启动服务器线程
    ConnectThread cThread = new ConnectThread(remoteDeviceList.getRemoteDevice(), MY_UUID, handler);
    cThread.start(); // 启动客户端线程
    mConnectThread = cThread;
    tvinfo.setText(String.format("正在与%s建立连接...", deviceName));
    // 注册一个Broadcast Receiver来监听BluetoothDevice.ACTION_ACL_DISCONNECTED,即与远程设备建立连接失败
    registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
  }
  /**
   * Start the ConnectedThread to begin managing a Bluetooth connection
   *
   * @param socket The BluetoothSocket on which the connection was made
   * @param device The BluetoothDevice that has been connected
   */
  public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
    if (D) Log.d(TAG, "connected");

    // Cancel the thread that completed the connection
    if (mConnectThread != null) {
      mConnectThread.cancel();
      mConnectThread = null;
    }

    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {
      mConnectedThread.cancel();
      mConnectedThread = null;
    }

    // Cancel the accept thread because we only want to connect to one device
    if (mAcceptThread != null) {
      mAcceptThread.cancel();
      mAcceptThread = null;
    }

    // Start the thread to manage the connection and perform transmissions
    mConnectedThread = new ConnectedThread(socket);
    mConnectedThread.start();

    // Send the name of the connected device back to the UI Activity
    Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
    Bundle bundle = new Bundle();
    bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());
    msg.setData(bundle);
    mHandler.sendMessage(msg);

    setState(STATE_CONNECTED);
  }
  /**
   * Start the ConnectedThread to begin managing a Bluetooth connection
   *
   * @param socket The BluetoothSocket on which the connection was made
   * @param device The BluetoothDevice that has been connected
   */
  public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {

    // Cancel the thread that completed the connection
    if (mConnectThread != null) {
      mConnectThread.cancel();
      mConnectThread = null;
    }

    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {
      mConnectedThread.cancel();
      mConnectedThread = null;
    }

    // Cancel the accept thread because we only want to connect to one
    // device
    if (mAcceptThread != null) {
      mAcceptThread.cancel();
      mAcceptThread = null;
    }

    // Start the thread to manage the connection and perform transmissions
    mConnectedThread = new ConnectedThread(socket);
    mConnectedThread.start();

    setState(STATE_CONNECTED);
  }
  /**
   * Start the chat service. Specifically start AcceptThread to begin a session in listening
   * (server) mode. Called by the Activity onResume()
   */
  public synchronized void start() {
    Log.d(TAG, "Bluetooth Service start()");

    // Cancel any thread attempting to make a connection
    if (mConnectThread != null && mState != STATE_CONNECTING) {
      Log.d(TAG, "connect thread null");
      mConnectThread.cancel();
      mConnectThread = null;
    }

    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {
      Log.d(TAG, "connected thread null");
      mConnectedThread.cancel();
      mConnectedThread = null;
    }

    // Start the thread to listen on a BluetoothServerSocket
    // if connected or connect is null (no trial yet), then wait for connection
    if (mAcceptThread == null) {
      Log.d(TAG, "accept thread reset");
      mAcceptThread = new AcceptThread();
      mAcceptThread.start();
    }
    setState(STATE_LISTEN);
  }
Example #9
0
  private synchronized void startAccept() {
    // Log.v("DistoX", "sync startAccept() ");
    if (mAcceptThread != null) {
      mAcceptRun = false;
      setAcceptState(STATE_NONE);
      try {
        mAcceptThread.join();
      } catch (InterruptedException e) {
      }
    }

    mAcceptRun = true;
    mType = STATE_LISTEN;
    mAcceptThread = new AcceptThread();
    mAcceptThread.start();
    setAcceptState(STATE_LISTEN);
  }
Example #10
0
    public BluetoothConnecting(
        OnConnectedListener onBtConnected, boolean alwaysClient, UUID serviceUuid) {
      mAlwaysClient = alwaysClient;
      mmBtConnected = onBtConnected;
      mServiceUuid = serviceUuid;
      mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
      if (mBluetoothAdapter == null) {
        throw new IllegalStateException("No Bluetooth adapter found.");
      }
      Random random = new Random();
      mCollisionResolution = new byte[2];
      random.nextBytes(mCollisionResolution);

      mAcceptThread = new AcceptThread();
      mChannel = mAcceptThread.getListeningPort();
      mAcceptThread.start();
    }
Example #11
0
 public synchronized void stop() {
   // Log.v("DistoX", "sync stop");
   if (mAcceptThread != null) {
     mAcceptThread.cancel();
     mAcceptThread = null;
   }
   setAcceptState(STATE_NONE);
   mType = STATE_NONE;
 }
  public synchronized void start() {
    DebugLog.i(TAG, "start");

    setState(STATE_LISTEN);

    if (mSecureAcceptThread == null) {
      DebugLog.i(TAG, "starting accept thread...");
      mSecureAcceptThread = new AcceptThread();
      mSecureAcceptThread.start();
    }
  }
 /**
  * Stops all running threads.
  *
  * @see com.example.drawfriends.BluetoothService#setState(int)
  */
 public synchronized void stop() {
   if (mConnectThread != null) {
     mConnectThread.cancel();
     mConnectThread = null;
   }
   if (mConnectedThread != null) {
     mConnectedThread.cancel();
     mConnectedThread = null;
   }
   if (mAcceptThread != null) {
     mAcceptThread.cancel();
     mAcceptThread = null;
   }
   setState(STATE_NONE);
 }
  /** Stop all threads */
  public synchronized void stop() {
    Log.d(TAG, "stop");

    if (mConnectThread != null) {
      mConnectThread.cancel();
      mConnectThread = null;
    }

    if (mConnectedThread != null) {
      mConnectedThread.cancel();
      mConnectedThread = null;
    }

    if (mSecureAcceptThread != null) {
      mSecureAcceptThread.cancel();
      mSecureAcceptThread = null;
    }

    if (mInsecureAcceptThread != null) {
      mInsecureAcceptThread.cancel();
      mInsecureAcceptThread = null;
    }
    setState(STATE_NONE);
  }
  /**
   * Start the ConnectedThread to begin managing a Bluetooth connection
   *
   * @param socket The BluetoothSocket on which the connection was made
   * @param device The BluetoothDevice that has been connected
   */
  public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
    if (D) Log.d(TAG, "connected");

    // Cancel the thread that completed the connection
    if (mConnectThread != null) {
      mConnectThread.cancel();
      mConnectThread = null;
    }

    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {
      mConnectedThread.cancel();
      mConnectedThread = null;
    }

    // Cancel the accept thread because we only want to connect to one device
    if (mAcceptThread != null) {
      mAcceptThread.cancel();
      mAcceptThread = null;
    }

    // Start the thread to manage the connection and perform transmissions
    mConnectedThread = new ConnectedThread(socket);
    mConnectedThread.start();

    // Send the name of the connected device back to the UI Activity

    // mHandler.obtainMessage(),Returns a new Message from the global message pool, and
    // also sets the what member of the returned Message.
    // 為msg 貼上what的tag
    Message msg = mHandler.obtainMessage(MainService.MESSAGE_DEVICE_NAME);

    Log.i(TAG, "device.getName() : " + device.getName());
    DeviceMappingAdapter deviceMappingAdapter = new DeviceMappingAdapter(mainContext);
    String deviceSn = deviceMappingAdapter.getDeviceSnById(device.getName());
    if (deviceSn != null) {
      Log.i(TAG, "泰博跑到陽明血壓計");
      setState(STATE_LISTEN);
      mHandler.obtainMessage(MainService.MESSAGE_CONNECTION_CLOSE, 1, -1).sendToTarget();
    } else {
      Bundle bundle = new Bundle();
      bundle.putString(MainService.DEVICE_NAME, device.getName());
      msg.setData(bundle);
      mHandler.sendMessage(msg);

      setState(STATE_CONNECTED);
    }
  }
  /** Stop all threads */
  public synchronized void stop() {
    Log.d("BTHandler", "destroying the connection at all...");

    if (mConnectThread != null) {
      mConnectThread.cancel();
      mConnectThread = null;
    }
    if (mConnectedThread != null) {
      mConnectedThread.cancel();
      mConnectedThread = null;
    }
    if (mAcceptThread != null) {
      mAcceptThread.cancel();
      mAcceptThread = null;
    }
    setState(STATE_NONE);
  }
Example #17
0
    @Override
    public void doConnectionHandover(NdefMessage handoverRequest, int handover, int record)
        throws IOException {

      byte[] remoteCollision = handoverRequest.getRecords()[handover + 1].getPayload();
      if (remoteCollision[0] == mCollisionResolution[0]
          && remoteCollision[1] == mCollisionResolution[1]) {
        return; // They'll have to try again.
      }
      boolean amServer =
          (remoteCollision[0] < mCollisionResolution[0]
              || (remoteCollision[0] == mCollisionResolution[0]
                  && remoteCollision[1] < mCollisionResolution[1]));

      if (mAlwaysClient) {
        amServer = false;
      }

      if (!mConnectionStarted) {
        synchronized (BluetoothConnecting.this) {
          if (!mConnectionStarted) {
            mConnectionStarted = true;
            mmBtConnected.beforeConnect(amServer);
          }
        }
      }
      if (!amServer) {
        // Not waiting for a connection:
        mAcceptThread.cancel();
        Uri uri = Uri.parse(new String(handoverRequest.getRecords()[record].getPayload()));
        UUID serviceUuid = UUID.fromString(uri.getPath().substring(1));
        int channel = -1;
        String channelStr = uri.getQueryParameter("channel");
        if (null != channelStr) {
          channel = Integer.parseInt(channelStr);
        }

        BluetoothDevice remoteDevice = mBluetoothAdapter.getRemoteDevice(uri.getAuthority());
        new ConnectThread(remoteDevice, serviceUuid, channel).start();
      }
    }
  /**
   * Stops any running threads and starts the thread that listens for incoming connections.
   *
   * @see com.example.drawfriends.BluetoothService.AcceptThread
   * @see com.example.drawfriends.BluetoothService#setState(int)
   */
  public synchronized void start() {

    // Cancel any thread attempting to make a connection
    if (mConnectThread != null) {
      mConnectThread.cancel();
      mConnectThread = null;
    }

    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {
      mConnectedThread.cancel();
      mConnectedThread = null;
    }

    // Start the thread to listen on a BluetoothServerSocket
    if (mAcceptThread == null) {
      mAcceptThread = new AcceptThread();
      mAcceptThread.start();
    }
    setState(STATE_LISTEN);
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_roomstayhost);
    Bundle extra = getIntent().getExtras();
    pseudo = extra.getString("pseudo");
    host = extra.getBoolean("host");
    listView = (ListView) findViewById(R.id.hostedGamesList);

    adapter =
        new ArrayAdapter<String>(
            this, android.R.layout.simple_list_item_1, android.R.id.text1, player) {
          public View getView(int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);

            /* Change le style du textView ayant pour id text1 */
            TextView textView = (TextView) view.findViewById(android.R.id.text1);

            textView.setTextColor(Color.parseColor("#8A0808"));
            textView.setBackgroundColor(Color.parseColor("#424242"));
            textView.setTextSize(20);

            return view;
          }
        };
    adapter.notifyDataSetChanged();
    // Assign adapter to ListView
    listView.setAdapter(adapter);

    if (host) {
      Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
      discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 1000);
      startActivity(discoverableIntent);
      serveur.start();
    }
  }
  /**
   * 打开连接
   *
   * @return 连接状态
   */
  public boolean connectDevice() {
    // 0、判断本机是否支持蓝牙设备
    if (mBluetoothAdapter == null) {
      showTips(R.string.device_local_unsupport_bluetooth);
      return false;
    }
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); // 获取所有已配对的设备
    // 1、没有配对的设备
    if (pairedDevices.size() <= 0) {
      showTips(
          String.format(
              mActivity.getResources().getString(R.string.device_idcard_no_bonded_devices),
              DEVICE_NAME));
      return false;
    }

    BluetoothDevice adaptedDevice = null;
    for (Iterator<BluetoothDevice> iterator = pairedDevices.iterator(); iterator.hasNext(); ) {
      BluetoothDevice device = (BluetoothDevice) iterator.next();
      log.i(TAG, "name=" + device.getName() + ",address=" + device.getAddress());
      if (DEVICE_NAME.equals(device.getName())) {
        adaptedDevice = device;
        break;
      }
    }

    // 2、没有合适的配对设备
    if (adaptedDevice == null) {
      showTips(
          String.format(
              mActivity.getResources().getString(R.string.device_idcard_no_bonded_devices),
              DEVICE_NAME));
      return false;
    }

    // 3、蓝牙设备没有打开时打开设备
    if (!mBluetoothAdapter.isEnabled()) {
      mBluetoothAdapter.enable();
    }

    // 创建服务器端的监听
    mAcceptThread = new AcceptThread();
    mAcceptThread.start();

    // 4、创建蓝牙Socket
    try {
      mBluetoothConnector = new BluetoothConnector(adaptedDevice, mBluetoothAdapter);
      // 5、连接读卡器设备
      mBluetoothSocketWrapper = mBluetoothConnector.connect();
      // 6、获取输入输出流
      mInputStream = mBluetoothSocketWrapper.getInputStream();
      mOutputStream = mBluetoothSocketWrapper.getOutputStream();

      // 7、连接成功后血压仪会发送"READY"过来,如果安卓设备成功接收到"READY"说明连接成功了,就可以发送"TOK"指令
      byte[] buffer = new byte[5];
      int length = mInputStream.read(buffer);
      if (length != 5
          || buffer[0] != 'R'
          || buffer[1] != 'E'
          || buffer[2] != 'A'
          || buffer[3] != 'D'
          || buffer[4] != 'Y') {
        showTips(R.string.device_connect_failure);
        return false;
      }

      // 结果应该是READY
      log.i(TAG, "read data=" + HexBinary.bytesToHexStringPrint(buffer, 0, length));

      // 8、如果buffer中是"READY"则继续,发送"TOK"指令
      byte[] sendCmd = new byte[] {0x54, 0x4f, 0x4b, (byte) 0xff, (byte) 0xff};
      mOutputStream.write(sendCmd);
      mOutputStream.flush();
      // 写入输出流后,要等待500ms,服务端处理延时500ms
      Thread.sleep(500);
      // 然后紧接着接收来自服务端也就是血压仪的返回信息,如果成功的话返回"OK"
      buffer = new byte[2];
      length = mInputStream.read(buffer);
      if (length != 2 || buffer[0] != 'O' || buffer[1] != 'K') {
        showTips(R.string.device_connect_failure);
        return false;
      }
      log.i(TAG, "跟设备连接成功!");
    } catch (IOException e) {
      e.printStackTrace();
      showTips(R.string.device_connect_exception);
      return false;
    } catch (InterruptedException e) {
      e.printStackTrace();
      showTips(R.string.device_connect_exception);
      return false;
    } finally {
      closeClientDevice();
    }
    showTips(R.string.device_connect_success);
    return true;
  }
 public AllThreads(Handler handler) {
   mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
   mHandler = handler;
   accept = new AcceptThread();
   accept.start();
 }
 public void previous(View v) {
   serveur.cancel();
   finish();
 }
 public void closeDevice() {
   if (mAcceptThread != null) {
     mAcceptThread.close();
   }
 }