Android Open Source - simple-android-bt Connect Thread

From Project

Back to project page simple-android-bt.


The source code is released under:

MIT License

If you think the Android project simple-android-bt listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package io.generalpurpose.sandbox;
/*from w  w  w . j  a v  a 2 s  . c o m*/
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

import java.util.UUID;

 * Created by nathan on 4/3/14.
public class ConnectThread extends Thread {
    private static final String TAG = "ConnectThread";
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;
    private UUID MY_UUID;
    private ManageSocketRunnable manageSocketRunnable;

    public ConnectThread(BluetoothDevice device, ManageSocketRunnable _manageSocketRunnable) {
        MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;
        manageSocketRunnable = _manageSocketRunnable;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            Log.d(TAG, "socket created successfully");
        } catch (IOException e) {
            Log.e(TAG, String.format("failed to create socket, error: %s",
        mmSocket = tmp;

    public void run() {
        // Cancel discovery because it will slow down the connection

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            Log.d(TAG, "Socket connected successfully!");
        } catch (IOException connectException) {
            Log.e(TAG, String.format("Socket failed to connect, reason = %s",
            // Unable to connect; close the socket and get out
            try {
            } catch (IOException closeException) { }

        // Do work to manage the connection (in a separate thread)

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
        } catch (IOException e) { }

Java Source Code List