Java Code Examples for android.bluetooth.BluetoothSocket

The following are top voted examples for showing how to use android.bluetooth.BluetoothSocket. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: bluetooth-chat-appliction   File: BluetoothChatService.java   Source Code and License 12 votes vote down vote up
public ConnectedThread(BluetoothSocket socket, String socketType) {
    Log.d(TAG, "create ConnectedThread: " + socketType);
    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;
    mState = STATE_CONNECTED;
}
 
Example 2
Project: ELM327   File: BluetoothIOGateway.java   Source Code and License 7 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 3
Project: BluetoothAPP   File: BluetoothUtil.java   Source Code and License 7 votes vote down vote up
/**
     * 连接蓝牙(2)
     *
     * @return
     */
    public static BluetoothSocket connectDevice(final Handler handler) {
        BluetoothSocket socket = null;
        try {
            Comment.SPP_UUID = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");
            socket = Comment.bluetoothDevice.createRfcommSocketToServiceRecord(Comment.SPP_UUID);
            socket.connect();
            handler.sendEmptyMessage(Comment.CONNECT);
        } catch (Exception e) {
            handler.sendEmptyMessage(2);
            try {
                if (socket!=null)
                socket.close();
            } catch (Exception closeException) {

            }
        }
        return socket;
}
 
Example 4
Project: dab-iot   File: BluetoothChatService.java   Source Code and License 6 votes vote down vote up
public ConnectedThread(BluetoothSocket socket, String socketType) {
    Log.d(TAG, "create ConnectedThread: " + socketType);
    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;
    mState = STATE_CONNECTED;
}
 
Example 5
Project: VR-One   File: BluetoothListener.java   Source Code and License 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) {
        Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
    }
    mmSocket = tmp;
    mState = STATE_CONNECTING;
}
 
Example 6
Project: VR-One   File: BluetoothListener.java   Source Code and License 6 votes vote down vote up
public ConnectedThread(BluetoothSocket socket, String socketType) {
    Log.d(TAG, "create ConnectedThread: " + socketType);
    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;
    mState = STATE_CONNECTED;
}
 
Example 7
Project: AndroidSDK2.0   File: BTAdt.java   Source Code and License 6 votes vote down vote up
/**
 * Bind boolean.
 *
 * @param socket the socket
 * @return the boolean
 */
public boolean bind( BluetoothSocket socket )
{

	mmSocket = socket;
	macAddress = mmSocket.getRemoteDevice().getAddress();

	// Get the BluetoothSocket input and output streams
	try
	{
		mmInStream = socket.getInputStream();
		mmOutStream = socket.getOutputStream();

		this.isRunning = true;
		// 펜 연결 후 맨 처음 펜정보를 요청한다.(프로토콜 2.0)
		startConnect();
		return true;
	}
	catch ( IOException e )
	{
		NLog.e( "[BTAdt/ConnectedThread] temporary sockets is not created", e );
	}

	return false;
}
 
Example 8
Project: Presenter-Client-Android   File: BluetoothPresenterControl.java   Source Code and License 6 votes vote down vote up
/**
 * Creates the connection thread that will connect to a given device.
 *
 * @param device The device to connect to
 */
ConnectThread(BluetoothDevice device) {
    mmDevice = device;
    BluetoothSocket tmp = null;

    // Get a BluetoothSocket for a connection with the given BluetoothDevice
    try {
        tmp = device.createRfcommSocketToServiceRecord(SERVICE_UUID);
    } catch (IOException e) {
        Log.e(TAG, "create socket failed", e);
    }
    mmSocket = tmp;
    mState = ServiceState.CONNECTING;

    // Notifiy the user that we are now connecting
    android.os.Message userNotification
            = mHandler.obtainMessage(ServiceState.CONNECTING.ordinal());
    mHandler.sendMessage(userNotification);
}
 
Example 9
Project: SmartRC   File: BluetoothChatService.java   Source Code and License 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) {
        Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
    }
    mmSocket = tmp;
}
 
Example 10
Project: Presenter-Client-Android   File: BluetoothPresenterControl.java   Source Code and License 6 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
 */
private 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;
    }

    // Start the thread to manage the connection and perform transmissions
    mConnectedThread = new ConnectedThread(socket, this, device);
    mConnectedThread.start();
}
 
Example 11
Project: Nird2   File: DroidtoothPlugin.java   Source Code and License 6 votes vote down vote up
@Override
public DuplexTransportConnection createKeyAgreementConnection(
		byte[] commitment, BdfList descriptor, long timeout) {
	if (!isRunning()) return null;
	String address;
	try {
		address = parseAddress(descriptor);
	} catch (FormatException e) {
		LOG.info("Invalid address in key agreement descriptor");
		return null;
	}
	// No truncation necessary because COMMIT_LENGTH = 16
	UUID uuid = UUID.nameUUIDFromBytes(commitment);
	if (LOG.isLoggable(INFO))
		LOG.info("Connecting to key agreement UUID " + uuid);
	BluetoothSocket s = connect(address, uuid.toString());
	if (s == null) return null;
	return new DroidtoothTransportConnection(this, s);
}
 
Example 12
Project: Nird2   File: DroidtoothPlugin.java   Source Code and License 6 votes vote down vote up
private void acceptContactConnections() {
	while (isRunning()) {
		BluetoothSocket s;
		try {
			s = socket.accept();
		} catch (IOException e) {
			// This is expected when the socket is closed
			if (LOG.isLoggable(INFO)) LOG.info(e.toString());
			return;
		}
		if (LOG.isLoggable(INFO)) {
			String address = s.getRemoteDevice().getAddress();
			LOG.info("Connection from " + scrubMacAddress(address));
		}
		backoff.reset();
		callback.incomingConnectionCreated(wrapSocket(s));
	}
}
 
Example 13
Project: Nird2   File: DroidtoothPlugin.java   Source Code and License 6 votes vote down vote up
@Override
public DuplexTransportConnection createKeyAgreementConnection(
		byte[] commitment, BdfList descriptor, long timeout) {
	if (!isRunning()) return null;
	String address;
	try {
		address = parseAddress(descriptor);
	} catch (FormatException e) {
		LOG.info("Invalid address in key agreement descriptor");
		return null;
	}
	// No truncation necessary because COMMIT_LENGTH = 16
	UUID uuid = UUID.nameUUIDFromBytes(commitment);
	if (LOG.isLoggable(INFO))
		LOG.info("Connecting to key agreement UUID " + uuid);
	BluetoothSocket s = connect(address, uuid.toString());
	if (s == null) return null;
	return new DroidtoothTransportConnection(this, s);
}
 
Example 14
Project: Nird2   File: DroidtoothPlugin.java   Source Code and License 6 votes vote down vote up
@Override
public BluetoothSocket call() throws Exception {
	// Repeat discovery until we connect or get interrupted
	while (true) {
		// Discover nearby devices
		LOG.info("Discovering nearby devices");
		List<String> addresses = discoverDevices();
		if (addresses.isEmpty()) {
			LOG.info("No devices discovered");
			continue;
		}
		// Connect to any device with the right UUID
		for (String address : addresses) {
			BluetoothSocket s = connect(address, uuid);
			if (s != null) {
				LOG.info("Outgoing connection");
				return s;
			}
		}
	}
}
 
Example 15
Project: Snach-Android   File: BluetoothActivity.java   Source Code and License 6 votes vote down vote up
public ConnectThread(BluetoothDevice device) {
    // Use a temporary object that is later assigned to mmSocket,
    // because mmSocket is final
    BluetoothSocket tmp = null;
    mmDevice = device;

    /*try {
        tmp = createBluetoothSocket(device);
    } catch (IOException e1) {
        e1.printStackTrace();
    }*/

    try {
        tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) { e.printStackTrace(); }

    /*try {
        tmp = createBluetoothSocket(device);
    } catch (IOException e) {
        e.printStackTrace();
    }*/

    mmSocket = tmp;
}
 
Example 16
Project: phonk   File: PBluetoothServer.java   Source Code and License 6 votes vote down vote up
private void connectToClient(final BluetoothSocket btSocketClient) throws IOException {
    MLog.d(TAG, "bbt connection to device: " + btSocketClient.getRemoteDevice().getName());

    final ConnectedDevice connectedDevice = new ConnectedDevice(btSocketClient);
    mServerConnections.add(connectedDevice);

    // callback
    if (mCallbackOnNewConnection != null) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                ReturnObject ret = new ReturnObject();
                ret.put("device", connectedDevice);
                ret.put("name", btSocketClient.getRemoteDevice().getName());
                ret.put("mac", btSocketClient.getRemoteDevice().getAddress());
                mCallbackOnNewConnection.event(ret);
            }
        });

    }

    connectedDevice.startThread();
}
 
Example 17
Project: SecretTalk   File: BluetoothChatService.java   Source Code and License 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) {
        Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
    }
    mmSocket = tmp;
    mState = STATE_CONNECTING;
}
 
Example 18
Project: grblcontroller   File: SerialThreadService.java   Source Code and License 6 votes vote down vote up
public ConnectThread(BluetoothDevice device, boolean secure) {
    mmDevice = device;
    BluetoothSocket tmp = null;
    mSocketType = secure ? "Secure" : "Insecure";

    try {
        if (secure) {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
        } else {
            tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
        }
    } catch (IOException | NullPointerException e) {
        Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
    }
    mmSocket = tmp;
    mState = STATE_CONNECTING;
}
 
Example 19
Project: grblcontroller   File: SerialThreadService.java   Source Code and License 6 votes vote down vote up
public ConnectedThread(BluetoothSocket socket, String socketType) {
    Log.d(TAG, "create ConnectedThread: " + socketType);
    mmSocket = socket;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;

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

    mmInStream = tmpIn;
    mmOutStream = tmpOut;
    mState = STATE_CONNECTED;
}
 
Example 20
Project: Lazy-Switches   File: BluetoothService.java   Source Code and License 6 votes vote down vote up
public ConnectThread(BluetoothDevice device) {
    // Use a temporary object that is later assigned to mmSocket,
    // because mmSocket is final
    BluetoothSocket tmp = null;
    mmDevice = device;

    // 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 uuid = Constants.myUUID;
        tmp = device.createRfcommSocketToServiceRecord(uuid);
    } catch (IOException e) {
        Log.e(Constants.TAG, "Create RFcomm socket failed", e);
    }
    mmSocket = tmp;
}
 
Example 21
Project: Lazy-Switches   File: BluetoothService.java   Source Code and 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 22
Project: LittleBitLouder   File: ClientThread.java   Source Code and License 6 votes vote down vote up
public ClientThread(BluetoothDevice device, Handler handler, boolean secure) {
    BluetoothSocket tempSocket = null;
    this.handler = handler;
    this.secure = secure;
    this.device = device;

    try {
        if (secure)
            tempSocket = device.createRfcommSocketToServiceRecord(UUID.fromString(Constants.UUID_STRING));
        else
            tempSocket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString(Constants.UUID_STRING));

    } catch (Exception e) {
        Log.e(TAG, e.toString());
    }
    this.socket = tempSocket;
}
 
Example 23
Project: LittleBitLouder   File: BluetoothConnector.java   Source Code and 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 24
Project: LittleBitLouder   File: BluetoothConnector.java   Source Code and License 6 votes vote down vote up
public FallbackBluetoothSocket(BluetoothSocket tmp, boolean isSecure) throws FallbackException {
    super(tmp);
    try {
        Class<?> clazz = tmp.getRemoteDevice().getClass();
        Class<?>[] paramTypes = new Class<?>[]{Integer.TYPE};

        String methodName = "createInsecureRfcommSocket";
        if (isSecure)
            methodName = "createRfcommSocket";

        Method m = clazz.getMethod(methodName, paramTypes);
        Object[] params = new Object[]{Integer.valueOf(1)};
        fallbackSocket = (BluetoothSocket) m.invoke(tmp.getRemoteDevice(), params);
    } catch (Exception e) {
        throw new FallbackException(e);
    }
}
 
Example 25
Project: dab-iot   File: BluetoothChatService.java   Source Code and License 6 votes vote down vote up
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_INSECURE);

    } catch (IOException e) {
        Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
    }
    mmSocket = tmp;
    mState = STATE_CONNECTING;
}
 
Example 26
Project: buildAPKsApps   File: BluetoothChatService.java   Source Code and License 6 votes vote down vote up
public void run() {
    if (D) Log.d(TAG, "BEGIN mAcceptThread" + this);
    setName("AcceptThread");
    BluetoothSocket socket = null;
    try {
    	// Listen for all 7 UUIDs
    	for (int i = 0; i < 7; i++) {
    		serverSocket = mAdapter.listenUsingRfcommWithServiceRecord(NAME, mUuids.get(i));
            socket = serverSocket.accept();
            if (socket != null) {
            	String address = socket.getRemoteDevice().getAddress();
             mSockets.add(socket);
             mDeviceAddresses.add(address);
             connected(socket, socket.getRemoteDevice());
            }	                    
    	}
    } catch (IOException e) {
        Log.e(TAG, "accept() failed", e);
    }
    if (D) Log.i(TAG, "END mAcceptThread");
}
 
Example 27
Project: buildAPKsApps   File: BluetoothChatService.java   Source Code and License 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 28
Project: xlight_android_native   File: BLEDeviceConnector.java   Source Code and License 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 29
Project: pass_the_bomb   File: ReceptionConnectionsThread.java   Source Code and License 6 votes vote down vote up
/**
 * Set the socket to listen and accept incoming connections
 */
public void run() {
    BluetoothSocket socket = null;
    // Keep listening until exception occurs or a socket is returned
    while (true) {
        try {
            socket = mmServerSocket.accept();
        } catch (IOException e) {
            break;
        }

        // If a connection was accepted
        if (socket != null) {
            // Do work to manage the connection (in a separate thread)
            new MessagingThread(socket).start();
            System.out.println("Socket accepted");
        }
    }
    cancel();
}
 
Example 30
Project: pass_the_bomb   File: ConnectionThread.java   Source Code and License 6 votes vote down vote up
/**
 * Creates the thread
 * @param playerToConnect player to connect to
 */
public ConnectionThread(Player playerToConnect) {
    //gets the device to connect to (the player's device)
    BluetoothDevice deviceToConnect = BluetoothServices.getmBluetoothAdapter().getRemoteDevice(playerToConnect.getMAC());
    System.out.println("device to connect to");
    System.out.println(deviceToConnect.getAddress());
    System.out.println(deviceToConnect.getName());
    System.out.println(deviceToConnect.toString());
    System.out.println("device to connect to");
    // Use a temporary object that is later assigned to mmSocket,
    // because mmSocket is final
    BluetoothSocket tmp = null;

    // Get a BluetoothSocket to connect with the given BluetoothDevice (that is a player)
    try {
        // MY_UUID is the app's UUID string, also used by the reception part of the code
        // creates and insecure RF socket
        tmp = deviceToConnect.createInsecureRfcommSocketToServiceRecord(MainActivity.uuid);
        System.out.println("Socket found!");

    } catch (IOException e) { }
    mmSocket = tmp;
}
 
Example 31
Project: pass_the_bomb   File: InitialReceptionConnectionsThread.java   Source Code and License 6 votes vote down vote up
/**
 * Run the socket and start creating connections and messaging threads
 */
public void run() {
    BluetoothSocket socket = null;
    // Keep listening until exception occurs or a socket is returned
    while (true) {
        try {
            socket = mmServerSocket.accept();
        } catch (IOException e) {
            break;
        }
        // If a connection was accepted
        if (socket != null) {
            // Do work to manage the connection (in a separate thread)
            System.out.println("Socket Accepted!!");
            new MessagingThread(socket).start();
            break;
        }
    }
    cancel();
}
 
Example 32
Project: pass_the_bomb   File: MessagingThread.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a messaging thread with the socket (and player behind socket).
 *
 * @param socket socket that represents the bluetooth connection
 */
public MessagingThread(BluetoothSocket socket) {
    System.out.println("Starting messaging thread " + socket.getRemoteDevice().getName());
    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) { }

    //the streams are used in order to receive and send data
    mmInStream = tmpIn;
    mmOutStream = tmpOut;

    //store this messaging thread in the map with all the messaging threads per player
    remoteDevice = mmSocket.getRemoteDevice();
    BluetoothServices.putInMessagingThreadMap(getRemotePlayer(),this);
}
 
Example 33
Project: Blockly   File: ConnectBluetoothThread.java   Source Code and License 6 votes vote down vote up
public ConnectBluetoothThread(BluetoothDevice device, BluetoothAdapter mBluetoothAdapter, Handler handler) {
    // Use a temporary object that is later assigned to mmSocket,
    // because mmSocket is final
    this.mBluetoothAdapter=mBluetoothAdapter;
    this.handler=handler;
    mmDevice = device;

    BluetoothSocket tmp = null;
    msg=new Message();

    // Get a BluetoothSocket to connect with the given BluetoothDevice
    try {
        // MY_UUID is the app's UUID string, also used by the server code
        String uuid="00001101-0000-1000-8000-00805f9b34fb";
        tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(uuid));
    } catch (IOException e) {
        Log.d(TAG, "ConnectBluetoothThread: 初始化uuid错误");
    }
    mmSocket = tmp;
}
 
Example 34
Project: buildAPKsSamples   File: BluetoothChatService.java   Source Code and License 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) {
        Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
    }
    mmSocket = tmp;
}
 
Example 35
Project: buildAPKsSamples   File: BluetoothChatService.java   Source Code and License 6 votes vote down vote up
public ConnectedThread(BluetoothSocket socket, String socketType) {
    Log.d(TAG, "create ConnectedThread: " + socketType);
    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 36
Project: UnityBluetoothPlugin   File: BluetoothService.java   Source Code and License 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 37
Project: ELM327   File: BluetoothIOGateway.java   Source Code and License 5 votes vote down vote up
public ConnectedThread(BluetoothSocket socket, String socketType)
{
    MyLog.d(TAG, "create ConnectedThread: " + socketType);

    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)
    {
        MyLog.e(TAG, "temp sockets not created", e);
    }

    mmInStream = tmpIn;
    mmOutStream = tmpOut;
}
 
Example 38
Project: VR-One   File: BluetoothListener.java   Source Code and License 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 39
Project: bluetooth-chat-appliction   File: BluetoothChatService.java   Source Code and License 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 40
Project: noise   File: BluetoothSyncService.java   Source Code and License 5 votes vote down vote up
@Override
public void run() {
    BluetoothSocket socket = null;

    while (started) {
        String macAddress = null;
        try {
            // This will block until there is a connection
            Log.d(TAG, "Bluetooth Classic server is listening for a client");
            socket = serverSocket.accept();
            macAddress = socket.getRemoteDevice().getAddress();
            if (!openConnections.containsKey(macAddress)) {
                openConnections.put(macAddress, true);
                StreamSync.bidirectionalSync(socket.getInputStream(), socket.getOutputStream());
            }
            socket.close();
        } catch (IOException connectException) {
            Log.e(TAG, "Failed to start a Bluetooth Classic connection as a server", connectException);

            try {
                if (socket != null)
                    socket.close();
            } catch (IOException closeException) {
                Log.e(TAG, "Failed to close a Bluetooth Classic connection as a server", closeException);
            }
        }
        if (macAddress != null)
            openConnections.remove(macAddress);
    }
}
 
Example 41
Project: AndroidSDK2.0   File: BTAdt.java   Source Code and License 5 votes vote down vote up
/**
 * Instantiates a new Connect thread.
 *
 * @param device the device
 */
public ConnectThread( BluetoothDevice device )
{
	mmDevice = device;

	BluetoothSocket tmp = null;
	if(mmDevice.getBluetoothClass() == null)
		mProtocolVer = 1;
	else if(mmDevice.getBluetoothClass().toString().equals( "51c") || mmDevice.getBluetoothClass().toString().equals( "2510"))
		mProtocolVer = 2;
	else
		mProtocolVer = 1;

	try
	{
		if(mProtocolVer == 2 && Build.VERSION.SDK_INT >= 19)
			tmp = device.createRfcommSocketToServiceRecord( NeoOne_UUID );
		else
			tmp = device.createInsecureRfcommSocketToServiceRecord( NeoOne_UUID );


	}
	catch ( Exception e )
	{
		NLog.e( "[BTAdt/ConnectThread] Socket Type : create() failed", e );
	}

	mmSocket = tmp;
}
 
Example 42
Project: AndroidSDK2.0   File: BTAdt.java   Source Code and License 5 votes vote down vote up
/**
	 * Connection 바인드
	 * 
	 * @param socket
	 */
	private void bindConnection( BluetoothSocket socket )
	{

//		new Handler(Looper.getMainLooper()).post( new Runnable()
//		{
//			@Override
//			public void run ()
//			{
//				Toast.makeText( context, "BluetoothSocket ProtocolVer=" + mProtocolVer, Toast.LENGTH_LONG ).show();
//			}
//		} );
		NLog.i( "[BTAdt] bindConnection by BluetoothSocket : " + socket.getRemoteDevice().getAddress() + ";mProtocolVer=" + mProtocolVer + ";COD=" + socket.getRemoteDevice().getBluetoothClass().getDeviceClass() + ";getBluetoothClass=" + socket.getRemoteDevice().getBluetoothClass().toString() );

		mConnectionThread = new ConnectedThread(mProtocolVer);

		if ( mConnectionThread.bind( socket ) )
		{
			mConnectionThread.start();
			this.onBinded();
		}
		else
		{
			mProtocolVer = 0;
			mConnectionThread = null;
		}
	}
 
Example 43
Project: Snach-Android   File: BluetoothActivity.java   Source Code and License 5 votes vote down vote up
private void manageConnectedSocket(BluetoothSocket mmSocket) {
        ConnectedThread connectedThread = new ConnectedThread(mmSocket);
        connectedThread.write('n');
        String s = connectedThread.read();
        while(!s.startsWith("0")) {
            Log.i("BT_STREAM", s);
            s = connectedThread.read();
        }
//        connectedThread.run();
    }
 
Example 44
Project: SmartOrnament   File: ConnectThread.java   Source Code and License 5 votes vote down vote up
public ConnectThread(BluetoothDevice device, BluetoothAdapter bluetoothAdapter, Handler handler) {
        mBluetoothAdapter=bluetoothAdapter;
        BluetoothSocket tmp = null;
        mDevice = device;
        mHandler=handler;
        try {
            //创建RFCOMM通道
            tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(UUID_STR));
        } catch (IOException e) {
//            Log.d(TAG, "createRfcommSocketToServiceRecord error!");
        }

        mSocket = tmp;
    }
 
Example 45
Project: journey-android-bluetooth-scale   File: BluetoothServiceThread.java   Source Code and License 5 votes vote down vote up
public BluetoothServiceThread(BluetoothService bluetoothService, BluetoothDevice bluetoothDevice) {
    this.bluetoothService = bluetoothService;

    BluetoothSocket bluetoothSocket = null;
    try {
        bluetoothSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(bluetoothService.getSppUuid());
    } catch (Throwable e) {
        Log.e(TAG, "could not create socket", e);
    }
    this.bluetoothSocket = bluetoothSocket;
}
 
Example 46
Project: journey-android-bluetooth-scale   File: BluetoothService.java   Source Code and License 5 votes vote down vote up
public final synchronized void connected(BluetoothSocket bluetoothSocket) {
    Log.i(TAG, "BluetoothService connected");
    this.close();
    this.bluetoothConnectedThread = new BluetoothConnectedThread(this, bluetoothSocket);
    this.bluetoothConnectedThread.start();
    setState(ConnectionState.CONNECTED);
}
 
Example 47
Project: Nird2   File: DroidtoothPlugin.java   Source Code and License 5 votes vote down vote up
@Override
public void poll(Collection<ContactId> connected) {
	if (!isRunning()) return;
	backoff.increment();
	// Try to connect to known devices in parallel
	Map<ContactId, TransportProperties> remote =
			callback.getRemoteProperties();
	for (Entry<ContactId, TransportProperties> e : remote.entrySet()) {
		final ContactId c = e.getKey();
		if (connected.contains(c)) continue;
		final String address = e.getValue().get(PROP_ADDRESS);
		if (StringUtils.isNullOrEmpty(address)) continue;
		final String uuid = e.getValue().get(PROP_UUID);
		if (StringUtils.isNullOrEmpty(uuid)) continue;
		ioExecutor.execute(new Runnable() {
			@Override
			public void run() {
				if (!running) return;
				BluetoothSocket s = connect(address, uuid);
				if (s != null) {
					backoff.reset();
					callback.outgoingConnectionCreated(c, wrapSocket(s));
				}
			}
		});
	}
}
 
Example 48
Project: Nird2   File: DroidtoothPlugin.java   Source Code and License 5 votes vote down vote up
@Override
public DuplexTransportConnection createConnection(ContactId c) {
	if (!isRunning()) return null;
	TransportProperties p = callback.getRemoteProperties().get(c);
	if (p == null) return null;
	String address = p.get(PROP_ADDRESS);
	if (StringUtils.isNullOrEmpty(address)) return null;
	String uuid = p.get(PROP_UUID);
	if (StringUtils.isNullOrEmpty(uuid)) return null;
	BluetoothSocket s = connect(address, uuid);
	if (s == null) return null;
	return new DroidtoothTransportConnection(this, s);
}
 
Example 49
Project: BluetoothChatDemo   File: BluetoothChatUtil.java   Source Code and License 5 votes vote down vote up
public ConnectThread(BluetoothDevice device) {
    mmDevice = device;
    BluetoothSocket tmp = null;
    // 得到一个bluetoothsocket
    try {
        mmSocket = device.createRfcommSocketToServiceRecord
                (SERVICE_UUID);
    } catch (IOException e) {
        Log.e(TAG, "create() failed", e);
        mmSocket = null;
    }
}
 
Example 50
Project: Nird2   File: DroidtoothPlugin.java   Source Code and License 5 votes vote down vote up
@Override
public BluetoothSocket call() throws Exception {
	BluetoothSocket s = connectionTask.call();
	InputStream in = s.getInputStream();
	while (in.available() == 0) {
		LOG.info("Waiting for data");
		Thread.sleep(1000);
	}
	LOG.info("Data available");
	return s;
}
 
Example 51
Project: Nird2   File: DroidtoothPlugin.java   Source Code and License 5 votes vote down vote up
@Override
public Callable<KeyAgreementConnection> listen() {
	return new Callable<KeyAgreementConnection>() {
		@Override
		public KeyAgreementConnection call() throws IOException {
			BluetoothSocket s = ss.accept();
			if (LOG.isLoggable(INFO))
				LOG.info(ID.getString() + ": Incoming connection");
			return new KeyAgreementConnection(
					new DroidtoothTransportConnection(
							DroidtoothPlugin.this, s), ID);
		}
	};
}
 
Example 52
Project: phonk   File: PBluetoothServer.java   Source Code and License 5 votes vote down vote up
public void run() {
    MLog.d(TAG, "bbt run " + mServerStarted);
    mServerStarted = true;
    MLog.d(TAG, "bbt run " + mServerStarted);

    while (mServerStarted) {
        try {
            BluetoothSocket serverSocket = mBluetoothServer.accept();
            MLog.d(TAG, "bbt accepting connection " + serverSocket.getRemoteDevice().getAddress());
            connectToClient(serverSocket); // since this is blocking, once we get a client we connect it
        } catch (IOException e) {
            MLog.d(TAG, "bbt BLUETOOTH error:" + e.getMessage());
        }
    }
}
 
Example 53
Project: Nird2   File: DroidtoothPlugin.java   Source Code and License 5 votes vote down vote up
@Override
public DuplexTransportConnection createConnection(ContactId c) {
	if (!isRunning()) return null;
	TransportProperties p = callback.getRemoteProperties().get(c);
	if (p == null) return null;
	String address = p.get(PROP_ADDRESS);
	if (StringUtils.isNullOrEmpty(address)) return null;
	String uuid = p.get(PROP_UUID);
	if (StringUtils.isNullOrEmpty(uuid)) return null;
	BluetoothSocket s = connect(address, uuid);
	if (s == null) return null;
	return new DroidtoothTransportConnection(this, s);
}
 
Example 54
Project: Nird2   File: DroidtoothPlugin.java   Source Code and License 5 votes vote down vote up
@Override
public BluetoothSocket call() throws Exception {
	BluetoothSocket s = connectionTask.call();
	InputStream in = s.getInputStream();
	while (in.available() == 0) {
		LOG.info("Waiting for data");
		Thread.sleep(1000);
	}
	LOG.info("Data available");
	return s;
}
 
Example 55
Project: SecretTalk   File: BluetoothChatService.java   Source Code and License 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 56
Project: BluetoothAPP   File: BluetoothManngerActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected BluetoothSocket doInBackground(BluetoothDevice... params) {
    if (Comment.bluetoothSocket != null) {
        try {
            Comment.bluetoothSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    Comment.bluetoothSocket = BluetoothUtil.connectDevice(mHandler);
    return Comment.bluetoothSocket;
}
 
Example 57
Project: BluetoothAPP   File: BluetoothManngerActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onPostExecute(BluetoothSocket socket) {
    DialogUtil.CancelProgress();
    if (socket == null || !socket.isConnected()) {
        ToastUtil.showShort(BluetoothManngerActivity.this, "连接打印机失败");
    } else {
        ToastUtil.showShort(BluetoothManngerActivity.this, "开始打印");
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.bluetooth_log);
        PrintUtil.printTest(Comment.bluetoothSocket, bitmap);
    }
    super.onPostExecute(socket);
}
 
Example 58
Project: Chorus-RF-Laptimer   File: BluetoothService.java   Source Code and License 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) {
    // 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;
    }

    // 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(BluetoothState.MESSAGE_DEVICE_NAME);
    Bundle bundle = new Bundle();
    bundle.putString(BluetoothState.DEVICE_NAME, device.getName());
    bundle.putString(BluetoothState.DEVICE_ADDRESS, device.getAddress());
    msg.setData(bundle);
    mHandler.sendMessage(msg);

    setState(BluetoothState.STATE_CONNECTED);
}
 
Example 59
Project: Chorus-RF-Laptimer   File: BluetoothService.java   Source Code and License 5 votes vote down vote up
public ConnectedThread(BluetoothSocket socket, String socketType) {
    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) { }

    mmInStream = tmpIn;
    mmOutStream = tmpOut;
}
 
Example 60
Project: Lazy-Switches   File: BluetoothService.java   Source Code and License 5 votes vote down vote up
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
    Log.d(Constants.TAG, "connected to: " + device.getName());

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

    setState(Constants.STATE_CONNECTED);
}