java - 无法以编程方式连接到蓝牙设备

标签 java android sockets bluetooth

我的目标是连接到已经配对的蓝牙设备。我已经获得了所有配对设备的名称,并将它们显示在 ListView 中。当我单击 ListView 中的任何设备名称时,如果它在范围内,它应该连接到该设备。

每当我尝试通过调用 mmSocket.connect() 连接到设备时我在如下所示的日志猫中收到此系统错误,然后它调用 mmSocket.close() :

06-22 17:40:50.617: W/System.err(25986): java.io.IOException: read failed, socket might closed or timeout, read ret: -1
06-22 17:40:50.618: W/System.err(25986):    at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:510)
06-22 17:40:50.619: W/System.err(25986):    at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:521)
06-22 17:40:50.619: W/System.err(25986):    at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:320)
06-22 17:40:50.619: W/System.err(25986):    at ik.learning.bluetooth.MainActivity$ConnectThread.run(MainActivity.java:233)

我不确定为什么会发生这种情况,有人可以帮助我吗?下面是我的代码:

public class MainActivity  extends Activity implements OnItemClickListener{

ArrayAdapter<String> listAdapter;
Button connectNew;
ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
IntentFilter filter;
BroadcastReceiver receiver;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
Handler mHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    init();

    if(btAdapter == null){
        Toast.makeText(this, "No bluetooth detected", Toast.LENGTH_LONG).show();
        finish();
    } else {
        if(!btAdapter.isEnabled()){
            turnOnBluetooth();
        }

        getPairedDevices();
        startDiscovery();

    }

    mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
            case SUCCESS_CONNECT:
                ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket) msg.obj);
                Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
                String s = "Successfully connected";
                connectedThread.write(s.getBytes());
                break;
            case MESSAGE_READ:  
                byte[] readBuff = (byte[]) msg.obj;
                String string = new String(readBuff);
                Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };

}

private void startDiscovery() {
    // TODO Auto-generated method stub
    btAdapter.cancelDiscovery();
    btAdapter.startDiscovery();
}

private void turnOnBluetooth() {
    // TODO Auto-generated method stub
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent, 1);
}

private void getPairedDevices() {
    // TODO Auto-generated method stub
    devicesArray = btAdapter.getBondedDevices();
    if(devicesArray.size() > 0){
        for(BluetoothDevice device : devicesArray){
            //listAdapter.add(device.getName()+"\n"+device.getAddress());
            pairedDevices.add(device.getName());//+"\n"+device.getAddress());
        }
    }
}

private void init() {
    connectNew = (Button) findViewById(R.id.btnConnectNew);
    listView = (ListView) findViewById(R.id.bluetoothlistView);
    listView.setOnItemClickListener(this);
    listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, 0);
    listView.setAdapter(listAdapter);
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    pairedDevices = new ArrayList<String>();
    filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    devices = new ArrayList<BluetoothDevice>();

    receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();

            if(BluetoothDevice.ACTION_FOUND.equals(action)){
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                devices.add(device);
                String s = "";
                for(int i = 0; i< pairedDevices.size(); i++){
                    if(device.getName().equals(pairedDevices.get(i))){
                        s = "PAIRED";
                        break;
                    }
                }
                listAdapter.add(device.getName()+" ("+s+") "+"\n"+device.getAddress());
            } 

            else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){

            }

            else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){

            }

            else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
                if(btAdapter.getState() == btAdapter.STATE_OFF){
                    turnOnBluetooth();
                }
            }

        }
    };

    registerReceiver(receiver, filter);

    filter  = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    registerReceiver(receiver, filter);

    filter  = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(receiver, filter);

    filter  = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(receiver, filter);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == RESULT_CANCELED){
        Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
    }
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    unregisterReceiver(receiver);
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub
    if(btAdapter.isDiscovering()){
        btAdapter.cancelDiscovery();
    }
    if(listAdapter.getItem(arg2).contains("PAIRED")){
        //Object[] o = devicesArray.toArray();
        BluetoothDevice selectedDevice = devices.get(arg2); 
        ConnectThread connect = new ConnectThread(selectedDevice);
        connect.start();
        Toast.makeText(getApplicationContext(), "Devices Paired", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(getApplicationContext(), "Devices Not Paired", Toast.LENGTH_SHORT).show();
    }

}


private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    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
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

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

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            Log.d("ConnectThread","try connect");
            //mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
            mmSocket.connect();

        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            connectException.printStackTrace();
            Log.d("ConnectThread","catch connect: "+connectException);

            try {
                Log.d("ConnectThread","try soccet close");
                mmSocket.close();
            } catch (IOException closeException) { 
                Log.d("ConnectThread","catch close: "+connectException);
            }
            return;
        }

        // Do work to manage the connection (in a separate thread)
        Log.d("ConnectThread","before manage connected socket");
        //manageConnectedSocket(mmSocket);
        mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();

    }

    /*private void manageConnectedSocket(BluetoothSocket mmSocket2) {
        // TODO Auto-generated method stub

    }*/

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

private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    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) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer;  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                buffer = new byte[1024];  // buffer store for the stream
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();

            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
}

最佳答案

在onClick List Item之后,您将获得蓝牙名称,使用该名称您可以通过调用BluetoothAdapter.getDefaultAdapter().getRemoteDevice(bluetoothDevice.getAddress());来获取蓝牙设备对象

这是连接蓝牙设备的示例代码..

//global variable
BluetoothSocket mBSocket;

// inside run() function
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter.isEnabled()) {
    try {
        for(BluetoothDevice bt: mBluetoothAdapter.getBondedDevices()) {
            if(bt.getName().equalsIgnoreCase(selectedDevice.getName())) {
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(bt.getAddress());
                mBluetoothAdapter.cancelDiscovery();

                mBSocket = device.createRfcommSocketToServiceRecord(SPP_UUID);
                mBSocket.connect();
                return mBSocket;
            }
        }
    } catch(IOException e) {
        if(mBSocket != null) {
            try {
                mBSocket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            mBSocket = null;
        }
        e.printStackTrace();
        return null;
    }
} 
return null;

希望有帮助。

关于java - 无法以编程方式连接到蓝牙设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24351267/

相关文章:

java - 如何使用 Java 对 AWS S3 SDK 的 getObject 方法进行单元测试?

java - Android Studio,回收 View

c# - 除了ICMP(Ping)以外,如何从LAN控制计算机是否处于打开状态?

java - 使用 toString() 访问隐藏字段是否存在任何问题

java - 从 .bat 文件运行 jar 文件时调整控制台大小

java - SHA256withECDSA签名算法的输出格式是什么?

android - 在 Corona SDK 中,如何将记分员放入我的应用程序中?

android - 如何从一个 fragment 切换到另一个 fragment android

Python线程错误

java - 检测 TCP/IP 数据包丢失