Java Code Examples for android.bluetooth.BluetoothSocket

The following examples show how to use android.bluetooth.BluetoothSocket. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: retroband   Source File: BluetoothManager.java    License: Apache License 2.0 7 votes vote down vote up
public ConnectedThread(BluetoothSocket socket) {
    Log.d(TAG, "create ConnectedThread");
    mmSocket = socket;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;

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

    mmInStream = tmpIn;
    mmOutStream = tmpOut;
}
 
Example 2
public ConnectThread(BluetoothDevice device, boolean secure) {
    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) {
        Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
    }
    mmSocket = tmp;
}
 
Example 3
Source Project: AndrOBD   Source File: BtCommService.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Start the BtWorkerThread to begin managing a Bluetooth connection
 *
 * @param socket The BluetoothSocket on which the connection was made
 * @param device The BluetoothDevice that has been connected
 */
private synchronized void connected(BluetoothSocket socket, BluetoothDevice
	                                                            device, final String socketType)
{
	log.log(Level.FINE, "connected, Socket Type:" + socketType);

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

	// Cancel any thread currently running a connection
	if (mBtWorkerThread != null)
	{
		mBtWorkerThread.cancel();
		mBtWorkerThread = null;
	}
	// Start the thread to manage the connection and perform transmissions
	mBtWorkerThread = new BtWorkerThread(socket, socketType);
	mBtWorkerThread.start();

       // we are connected -> signal connection established
       connectionEstablished(device.getName());
   }
 
Example 4
Source Project: ClassicBluetooth   Source File: CbtClientService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 初始化
 *
 * @return
 */
public void init(BluetoothAdapter bluetoothAdapter, BluetoothDevice device, ConnectDeviceCallback callBack) {
    mCallBack = callBack;
    if (mBluetoothDevice != null) {
        if (mBluetoothDevice.getAddress().equals(device.getAddress())) {
            mCallBack.connectSuccess(mBluetoothSocket, mBluetoothDevice);
            return;
        } else {
            cancel();
        }
    }

    mBluetoothAdapter = bluetoothAdapter;
    mBluetoothDevice = device;
    BluetoothSocket tmp = null;
    try {
        //尝试建立安全的连接
        tmp = mBluetoothDevice.createRfcommSocketToServiceRecord(CbtConstant.CBT_UUID);
    } catch (IOException e) {
        mCallBack.connectError(e);
    }
    mBluetoothSocket = tmp;
    connect();
}
 
Example 5
Source Project: SimpleBluetoothLibrary   Source File: BluetoothService.java    License: Apache License 2.0 6 votes vote down vote up
public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            bluetoothSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            // Get the input and output streams, using temp objects because
            // member streams are final
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
//                Log.d("ConnectedThread", e.getMessage());
            }

            mInputStream = tmpIn;
            mOutputStream = tmpOut;
        }
 
Example 6
public ConnectedThread(BluetoothSocket socket) {
    Log.d(TAG, "create ConnectedThread: ");
    mSocket = socket;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;

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

    mInputStream = tmpIn;
    mOutputStream = tmpOut;
}
 
Example 7
Source Project: PolarHeartRateApplication   Source File: ConnectThread.java    License: MIT License 6 votes vote down vote up
public ConnectThread(BluetoothDevice device, MainActivity ac) {
	// Use a temporary object that is later assigned to mmSocket,
	// because mmSocket is final
	Log.i("ConnectThread", "Starting connectThread");
	this.ac=ac;
	BluetoothSocket tmp = null;
	mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

	// Get a BluetoothSocket to connect with the given BluetoothDevice
	try {
		// MY_UUID is the app's UUID string, also used by the server code
		UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
		tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
	} catch (IOException ignored) {
		Log.e("ConnectThread", "Error on getting the device");
	}
	mmSocket = tmp;

}
 
Example 8
Source Project: DataLogger   Source File: BluetoothConnector.java    License: MIT License 6 votes vote down vote up
private boolean selectSocket() throws IOException {
    if (candidate >= uuidCandidates.size()) {
        return false;
    }

    BluetoothSocket tmp;
    UUID uuid = uuidCandidates.get(candidate++);

    Log.e("BT", "===> Attempting to connect to Protocol: " + uuid);
    if (secure) {
        tmp = device.createRfcommSocketToServiceRecord(uuid);
    } else {
        tmp = device.createInsecureRfcommSocketToServiceRecord(uuid);
    }
    bluetoothSocket = new NativeBluetoothSocket(tmp);

    return true;
}
 
Example 9
Source Project: DataLogger   Source File: BluetoothConnectionHelper.java    License: MIT License 6 votes vote down vote up
public ConnectedThread(BluetoothSocket socket, int index) {
//            Log.d(TAG, "create ConnectedThread");
            mmSocket = socket;
            mIndex = index;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "::ConnectedThread Input/Output stream sockets not created", e);
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }
 
Example 10
Source Project: EFRConnect-android   Source File: BluetoothServer.java    License: Apache License 2.0 6 votes vote down vote up
public void run() {
    BluetoothSocket socket;
    // Keep listening until exception occurs or a socket is returned
    while (true) {
        try {
            socket = serverSocket.accept();
        } catch (IOException e) {
            if (!closing) {
                Log.e("BluetoothServer", "Error in Bluetooth Server Thread" + e);
                Timber.e(e, "Error in Bluetooth Server Thread");
            }
            break;
        }
        // If a connection was accepted
        if (socket != null) {
            // Do work to manage the connection (in a separate thread)
            manageConnectedSocket(socket);
            cancel();
            break;
        }
    }
}
 
Example 11
Source Project: ELM327   Source File: BluetoothIOGateway.java    License: Apache License 2.0 6 votes vote down vote up
public ConnectThread(BluetoothDevice device, boolean secure)
{
    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)
    {
        MyLog.e(TAG, "Socket Type: " + mSocketType + " create() failed", e);
    }

    mmSocket = tmp;
}
 
Example 12
Source Project: BTChat   Source File: BluetoothManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
public ConnectedThread(BluetoothSocket socket) {
    Log.d(TAG, "create ConnectedThread");
    mmSocket = socket;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;

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

    mmInStream = tmpIn;
    mmOutStream = tmpOut;
}
 
Example 13
Source Project: mytracks   Source File: BluetoothConnectionManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Starts the ConnectedThread to read data.
 * 
 * @param bluetoothSocket the bluetooth socket
 * @param bluetoothDevice the bluetooth device
 */
private synchronized void connected(
    BluetoothSocket bluetoothSocket, BluetoothDevice bluetoothDevice) {
  cancelThreads();

  connectedThread = new ConnectedThread(bluetoothSocket);
  connectedThread.start();

  // Send the device name to the handler
  Message message = handler.obtainMessage(MESSAGE_DEVICE_NAME);
  Bundle bundle = new Bundle();
  bundle.putString(KEY_DEVICE_NAME, bluetoothDevice.getName());
  message.setData(bundle);
  handler.sendMessage(message);

  setState(Sensor.SensorState.CONNECTED);
}
 
Example 14
Source Project: esc-pos-android   Source File: BTService.java    License: Apache License 2.0 6 votes vote down vote up
private synchronized void onDeviceConnected(BluetoothSocket socket, BluetoothDevice device) {
  cancelAllThreads();

  listenThread = new ListenThread(socket);
  listenThread.start();

  listenThread = new ListenThread(socket);
  listenThread.start();

  if (deviceCallbacks != null) {
    mainHandler.post(new Runnable() {
      @Override
      public void run() {
        deviceCallbacks.onConnected();
      }
    });
  }
  Log.e(TAG, "Device " + device.getName() + " [" + device.getAddress() + "] — connected");
  this.setState(STATE_CONNECTED);
}
 
Example 15
Source Project: UnityBluetoothPlugin   Source File: BluetoothService.java    License: Apache License 2.0 6 votes vote down vote up
public ConnectedThread(BluetoothSocket socket) {
    Log.d(TAG, "create ConnectedThread");
    mmSocket = socket;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;

    try {
        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();
    } catch (IOException e) {
        Log.e(TAG, "temp sockets not created", e);
    }

    mmInStream = tmpIn;
    mmOutStream = tmpOut;
}
 
Example 16
Source Project: PHONK   Source File: PBluetoothClient.java    License: GNU General Public License v3.0 6 votes vote down vote up
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
    MLog.d(TAG, "connected");

    changeStatus(CONNECTED, device);
    mDevice = device;

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

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

    // Start the thread to manage the connection and perform transmissions
    mConnectedThread = new ConnectedThread(socket, device);
    mConnectedThread.start();
}
 
Example 17
Source Project: tilt-game-android   Source File: BluetoothClientService.java    License: MIT License 6 votes vote down vote up
/**
 * Start the CommunicationThread to begin managing a Bluetooth connection
 *
 * @param socket The BluetoothSocket on which the connection was made
 * @param device The BluetoothDevice that has been connected
 */
private synchronized void connected(BluetoothSocket socket, BluetoothDevice device, final String socketType) {
    if (_debug) Log.d(TAG, "connected: ");

    cancelConnectThread();
    cancelCommunicationThread(_communicationThread);

    _communicationThread = createCommunicationThread(socket, device);

    // Send the name of the connected device back to the UI Activity
    Bundle bundle = new Bundle();
    bundle.putString(ServiceMessageKeys.DEVICE_NAME, device.getName());
    bundle.putString(ServiceMessageKeys.DEVICE_ADDRESS, device.getAddress());
    sendMessage(ServiceMessageType.MESSAGE_DEVICE_CONNECTED, bundle);

    setState(STATE_CONNECTED);
}
 
Example 18
Source Project: SmartOrnament   Source File: ConnectedThread.java    License: Apache License 2.0 6 votes vote down vote up
public ConnectedThread(BluetoothSocket socket, Context context,Handler handler) {
    vibrator = (Vibrator) context.getSystemService(VIBRATOR_SERVICE);
    mSocket = socket;//被管理的Socket
    mHandler=handler;
    this.context=context;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;
    //无论是客户端的Socket还是服务端的Socket,都有输入输出流
    try {
        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();
    } catch (IOException e) {  }
    mInStream = tmpIn;
    mOutStream = tmpOut;
    // 获得远程设备的输出缓存字符流,相当于找了一个大的管道,可以通向远程设备,发数据的必经管道
    mBw = new BufferedWriter(new PrintWriter(mOutStream));

    //mHandler=new Handler(Looper.getMainLooper());
}
 
Example 19
Source Project: Android-Simple-Bluetooth-Example   Source File: ConnectedThread.java    License: MIT License 6 votes vote down vote up
public ConnectedThread(BluetoothSocket socket, Handler handler) {
    mmSocket = socket;
    mHandler = handler;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;

    // Get the input and output streams, using temp objects because
    // member streams are final
    try {
        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();
    } catch (IOException e) { }

    mmInStream = tmpIn;
    mmOutStream = tmpOut;
}
 
Example 20
Source Project: Android-HC05-App   Source File: BluetoothService.java    License: MIT License 6 votes vote down vote up
public ConnectedThread(BluetoothSocket socket) {
    mmSocket = socket;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;

    // Get the input and output streams, using temp objects because
    // member streams are final
    try {
        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();
    } catch (IOException e) {
        Log.e(Constants.TAG, "Temp sockets not created", e);
    }

    mmInStream = tmpIn;
    mmOutStream = tmpOut;
}
 
Example 21
Source Project: retrowatch   Source File: BluetoothManager.java    License: Apache License 2.0 6 votes vote down vote up
public ConnectedThread(BluetoothSocket socket) {
    Log.d(TAG, "create ConnectedThread");
    mmSocket = socket;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;

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

    mmInStream = tmpIn;
    mmOutStream = tmpOut;
}
 
Example 22
Source Project: connectivity-samples   Source File: BluetoothChatService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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, final String socketType) {
    Log.d(TAG, "connected, Socket Type:" + socketType);

    // 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 (mSecureAcceptThread != null) {
        mSecureAcceptThread.cancel();
        mSecureAcceptThread = null;
    }
    if (mInsecureAcceptThread != null) {
        mInsecureAcceptThread.cancel();
        mInsecureAcceptThread = null;
    }

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

    // Send the name of the connected device back to the UI Activity
    Message msg = mHandler.obtainMessage(Constants.MESSAGE_DEVICE_NAME);
    Bundle bundle = new Bundle();
    bundle.putString(Constants.DEVICE_NAME, device.getName());
    msg.setData(bundle);
    mHandler.sendMessage(msg);
    // Update UI title
    updateUserInterfaceTitle();
}
 
Example 23
public SerialIOThread(BluetoothSocket rfcommSocket, MessageHashTableBase hashTable) {
    super();
    this.hashTable = hashTable;

    mRfCommSocket = rfcommSocket;
    try {
        mOutputStream = mRfCommSocket.getOutputStream();
        mInputStream = mRfCommSocket.getInputStream();
    } catch (IOException e) {
        log.error("Unhandled exception", e);
    }
    this.start();
}
 
Example 24
Source Project: coursera-android   Source File: ConnectionThread.java    License: MIT License 5 votes vote down vote up
ConnectionThread(BluetoothSocket socket, Handler handler){
	super();
	mBluetoothSocket = socket;
	mHandler = handler;
	try {
		mInStream = mBluetoothSocket.getInputStream();
		mOutStream = mBluetoothSocket.getOutputStream();
	} catch (IOException e) {
	}
}
 
Example 25
/**
 * 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(CaptureActivity.MESSAGE_DEVICE_NAME);
    Bundle bundle = new Bundle();
    bundle.putString(CaptureActivity.DEVICE_NAME, device.getName());
    msg.setData(bundle);
    mHandler.sendMessage(msg);

    setState(STATE_CONNECTED);
}
 
Example 26
Source Project: EasyBluetoothFrame   Source File: Connect.java    License: Apache License 2.0 5 votes vote down vote up
public Connect(BluetoothSocket socket) {
    executor = Executors.newFixedThreadPool(2);
    writeThread = new ConnectedThread(socket, ConnectedThread.WRITE, null);
    readThread = new ConnectedThread(socket, ConnectedThread.READ, null);
    executor.execute(writeThread);
    executor.execute(readThread);

}
 
Example 27
public ConnectThread(BluetoothDevice device) {
    BluetoothSocket tmp = null;

    // Get a BluetoothSocket for a connection with the given BluetoothDevice
    try {
        tmp = device.createInsecureRfcommSocketToServiceRecord(CONNECT_UUID);
    } catch (IOException e) {
        Log.e(TAG, "create() failed", e);
    }
    mSocket = tmp;
}
 
Example 28
static void sendPacket(BluetoothSocket socket, byte[] data) throws IOException, InterruptedException {
        OutputStream o = socket.getOutputStream();
        InputStream i = socket.getInputStream();
        byte[] packet = new byte[data.length + 3];
        packet[0] = 0x3e;
        packet[packet.length - 1] = 0x3c;
        byte crc = 0;
        for (int j = 0; j < data.length; j++) {
            crc += data[j];
            packet[j + 1] = data[j];
        }
        packet[packet.length - 2] = crc;
        o.write(packet);

        byte[] buffer = new byte[256];
        Date date = new Date();
        while (new Date().getTime() - date.getTime() < 200) {
            if (i.available() > 0) {
                int r = i.read(buffer);
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < r; j++) {
                    sb.append(String.format(" %02x", buffer[j]));
                }
//                Log.i(TAG, "Read: " + r + " bytes:" + sb);
                break;
            }
            Thread.sleep(50);
        }
    }
 
Example 29
Source Project: osr-android-app   Source File: SocketRunnable.java    License: Apache License 2.0 5 votes vote down vote up
protected SocketRunnable(StringBuffer throttle, StringBuffer steering, StringBuffer roverFace, StringBuffer servo, BluetoothSocket socket, StringBuffer exit,StringBuffer connectedStatus){
    this.mThrottle = throttle;
    this.mSteering = steering;
    this.mRoverFace = roverFace;
    this.mBluetoothSocket = socket;
    this.mServo = servo;
    this.mExit = exit;
    this.mConnectedStatus = connectedStatus;
}
 
Example 30
public synchronized void connected(BluetoothSocket socket,
		BluetoothDevice device)
{
	if (D)
		Log.d(TAG, "connected");

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

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

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

	mConnectedThread = new ConnectedThread(socket);
	mConnectedThread.start();

	Message msg = mHandler.obtainMessage(MainActivity.MESSAGE_DEVICE_NAME);
	Bundle bundle = new Bundle();
	bundle.putString(MainActivity.DEVICE_NAME, device.getName());
	msg.setData(bundle);
	mHandler.sendMessage(msg);

	setState(STATE_CONNECTED);
}