android.bluetooth.BluetoothSocket Java Examples

The following examples show how to use android.bluetooth.BluetoothSocket. 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 File: BTService.java    From esc-pos-android with 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 #2
Source File: BluetoothService.java    From UnityBluetoothPlugin with 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 #3
Source File: PBluetoothClient.java    From PHONK with 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 #4
Source File: BluetoothClientService.java    From tilt-game-android with 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 #5
Source File: ConnectedThread.java    From SmartOrnament with 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 #6
Source File: ConnectedThread.java    From Android-Simple-Bluetooth-Example with 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 #7
Source File: BluetoothService.java    From Android-HC05-App with 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 #8
Source File: BluetoothManager.java    From retrowatch with 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 #9
Source File: BluetoothManager.java    From retroband with 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 #10
Source File: BluetoothChatService.java    From connectivity-samples with 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 #11
Source File: SerialIOThread.java    From AndroidAPS with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #12
Source File: ConnectionThread.java    From coursera-android with 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 #13
Source File: BluetoothService.java    From Android-Bluetooth-Fingerprint with 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) {
    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 #14
Source File: Connect.java    From EasyBluetoothFrame with 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 #15
Source File: DirectMessageSession.java    From gilgamesh with GNU General Public License v3.0 5 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) {
        Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
    }
    mmSocket = tmp;
}
 
Example #16
Source File: SyncStreamingService.java    From boogie-board-sync-sdk-android with MIT License 5 votes vote down vote up
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 #17
Source File: TaskerFireReceiver.java    From sony-headphones-control with GNU General Public License v3.0 5 votes vote down vote up
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 #18
Source File: BtCommService.java    From AndrOBD with GNU General Public License v3.0 5 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 #19
Source File: SocketRunnable.java    From osr-android-app with 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 #20
Source File: CbtClientService.java    From ClassicBluetooth with Apache License 2.0 5 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 #21
Source File: BluetoothChatService.java    From Car_remote_control with GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example #22
Source File: BluetoothService.java    From SimpleBluetoothLibrary with Apache License 2.0 5 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 #23
Source File: SerialInterface_BT.java    From PodEmu with GNU General Public License v3.0 5 votes vote down vote up
public ConnectThread(BluetoothDevice device)
        {
            mmDevice = device;
            BluetoothSocket tmp = null;

            if(!btAdapter.isEnabled())
            {
                mmSocket = null;
                this.cancel();
//                mConnectedThread.cancel();
                PodEmuService.stopService(baseContext);
                return;
            }

            // Get a BluetoothSocket for a connection with the
            // given BluetoothDevice
            try
            {
                PodEmuLog.debug("SIBT: ConnectThread connecting with btdev_uuid_idx=" + btdev_uuid_idx);
                setState(STATE_CONNECTING);
                tmp = device.createRfcommSocketToServiceRecord(BTDEV_UUID[btdev_uuid_idx]);
            }
            catch (IOException e)
            {
                PodEmuLog.debug("SIBT: ConnectThread createRfcomm() failed");
                PodEmuLog.printStackTrace(e);
            }
            mmSocket = tmp;
        }
 
Example #24
Source File: BondedListActivity.java    From ClassicBluetooth with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化列表
 */
private void initList() {
    mRv.setLayoutManager(new LinearLayoutManager(mContext));
    mRv.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL));
    mBondedListAdapter = new BondedListAdapter(null);
    mRv.setAdapter(mBondedListAdapter);
    mBondedListAdapter.setOnItemClickListener(
            (adapter, view, position) -> {
                BluetoothDevice item = mBondedListAdapter.getItem(position);
                CbtManager
                        .getInstance()
                        .connectDevice(item, new ConnectDeviceCallback() {
                            @Override
                            public void connectSuccess(BluetoothSocket socket, BluetoothDevice device) {
                                Toast.makeText(mContext, "连接成功!", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(mContext, SendDataActivity.class));
                            }

                            @Override
                            public void connectError(Throwable throwable) {
                                CbtLogs.e(throwable.getMessage());
                                Toast.makeText(mContext, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        });
            }
    );

    List<BluetoothDevice> bondedDevices = CbtManager.getInstance().getBondedDevices();
    mBondedListAdapter.setNewData(bondedDevices);
}
 
Example #25
Source File: SyncStreamingService.java    From boogie-board-sync-sdk-android with MIT License 5 votes vote down vote up
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 #26
Source File: BluetoothActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 5 votes vote down vote up
private void sendMessage(BluetoothSocket socket, String message) {
  OutputStream outputStream;
  try {
    outputStream = socket.getOutputStream();

    // Add a stop character.
    byte[] byteArray = (message + " ").getBytes();
    byteArray[byteArray.length-1] = 0;
    outputStream.write(byteArray);
  } catch (IOException e) {
    Log.e(TAG, "Failed to send message: " + message, e);
  }
}
 
Example #27
Source File: BluetoothServerService.java    From tilt-game-android with MIT License 5 votes vote down vote up
private synchronized void accepted(BluetoothSocket socket, BluetoothDevice device, String socketType) {
    if (_debug) Log.d(TAG, "accepted, Socket Type:" + socketType);

    // Start the thread to manage the connection and perform transmissions
    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_ADDED, bundle);
}
 
Example #28
Source File: blueToothDemo.java    From bluetooth with Apache License 2.0 5 votes vote down vote up
public ConnectThread(BluetoothDevice device) {
    mmDevice = device;
    BluetoothSocket tmp = null;

    // Get a BluetoothSocket for a connection with the
    // given BluetoothDevice
    try {
        tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) {
        mkmsg("Client connection failed: "+e.getMessage().toString()+"\n");
    }
    socket = tmp;
 
}
 
Example #29
Source File: ConnectThread.java    From PolarHeartRateApplication with MIT License 5 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 #30
Source File: BluetoothConnector.java    From DataLogger with MIT License 5 votes vote down vote up
public FallbackBluetoothSocket(BluetoothSocket tmp) throws FallbackException {
    super(tmp);
    try {
        Class<?> clazz = tmp.getRemoteDevice().getClass();
        Class<?>[] paramTypes = new Class<?>[]{Integer.TYPE};
        Method m = clazz.getMethod("createRfcommSocket", paramTypes);
        Object[] params = new Object[]{Integer.valueOf(1)};
        fallbackSocket = (BluetoothSocket) m.invoke(tmp.getRemoteDevice(), params);
    } catch (Exception e) {
        throw new FallbackException(e);
    }
}