Android的蓝牙无法连接 [英] android bluetooth can't connect

查看:291
本文介绍了Android的蓝牙无法连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直有这个问题了一会儿,一直没能找到答案。

I've been having this problem for a while and haven't been able to figure it out.

我有一个Android的应用程序,使在ListView所有配对设备。当您单击列表中的项目之一,它会发起一个请求连接到蓝牙设备。

I have a android application that puts all paired devices in a listview. When you click one of the list items, it will initiate a request to connect to that bluetooth device.

我可以与他们的地址没有问题的设备列表。 现在的问题是,一旦我尝试连接,我得到一个IOException对Socket.connect()的;

I can get the list of devices with their addresses no problem. The problem is that once I try to connect I get an IOException on socket.connect();

错误信息如下: 连接读取失败,插座可能会关闭或超时,读RET:-1

下面是我的code。 任何建议将是AP preciated。我是pretty的停留在此。

Here is my code. ANY suggestions would be appreciated. I'm pretty stuck on this.

供参考:在的onEvent的方法是简化回调...这部分作品库。 当用户点击列表中的项目该方法被称为公共无效的onEvent(EventMessage.DeviceSelected事件)

fyi: the "onEvent" methods is a library that simplifies callbacks...that part works. When the user clicks on a list items this method is called "public void onEvent(EventMessage.DeviceSelected event)"

public class EcoDashActivity extends BaseActivity {

public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");


private BluetoothAdapter mBluetoothAdapter;
private int REQUEST_ENABLE_BT = 100;
private ArrayList<BluetoothDevice> mDevicesList;
private BluetoothDeviceDialog mDialog;
private ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();


@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);

    mDevicesList = new ArrayList<BluetoothDevice>();

    // Register the BroadcastReceiver
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(mReceiver, filter);

    setupBluetooth();
}

private void setupBluetooth() {
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        // Device does not support Bluetooth
        Toast.makeText(this, "Device does not support Bluetooth", Toast.LENGTH_SHORT).show();
    }

    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    } else {
        searchForPairedDevices();
        mDialog = new BluetoothDeviceDialog(this, mDevicesList);
        mDialog.show(getFragmentManager(), "");
    }

}

private void searchForPairedDevices() {

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    // If there are paired devices
    if (pairedDevices.size() > 0) {
        // Loop through paired devices
        for (BluetoothDevice device : pairedDevices) {
            // Add the name and address to an array adapter to show in a ListView
            mDevices.add(device.getName() + "\n" + device.getAddress());
            mDevicesList.add(device);
        }
    }
}


private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // Add the name and address to an array adapter to show in a ListView
            mDevicesList.add(device);
        }
    }
};


@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(mReceiver);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
        if (resultCode == RESULT_OK) {
            Toast.makeText(this, "BT turned on!", Toast.LENGTH_SHORT).show();
            searchForPairedDevices();

            mDialog = new BluetoothDeviceDialog(this, mDevicesList);
            mDialog.show(getFragmentManager(), "");
        }
    }

    super.onActivityResult(requestCode, resultCode, data);
}


public void onEvent(EventMessage.DeviceSelected event) {

    mDialog.dismiss();

    BluetoothDevice device = event.getDevice();

    ConnectThread connectThread = new ConnectThread(device);
    connectThread.start();
}


public 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() {
        setName("ConnectThread");
        // Cancel discovery because it will slow down the connection
        mBluetoothAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            Log.d("kent", "trying to connect to device");
            mmSocket.connect();
            Log.d("kent", "Connected!");
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                Log.d("kent", "failed to connect");

                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        Log.d("kent", "Connected!");
    }

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

下面是我的logcat的。 pretty的短。

Here is my logcat. Pretty short.

07-22 10:37:05.129: DEBUG/kent(17512): trying to connect to device
07-22 10:37:05.129: WARN/BluetoothAdapter(17512): getBluetoothService() called with no BluetoothManagerCallback
07-22 10:37:05.129: DEBUG/BluetoothSocket(17512): connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[98]}
07-22 10:37:40.757: DEBUG/dalvikvm(17512): GC_CONCURRENT freed 6157K, 9% free 62793K/68972K, paused 7ms+7ms, total 72ms
07-22 10:38:06.975: DEBUG/kent(17512): failed to connect
07-22 10:38:06.975: DEBUG/kent(17512): read failed, socket might closed or timeout, read ret: -1

这是最后一行是在try / catch的捕获一节中......我只是记录错误消息。

That last line is in the "Catch" section of a try/catch...I'm just logging the error message.

请注意,有试图连接到装置和无法连接

Please note, there is about a 20 second gap between "trying to connect to device" and "failed to connect"

推荐答案

果冻豆蓝牙堆栈是从其他版本的明​​显不同。

The jelly bean bluetooth stack is markedly different from the other versions.

这可能会帮助:<一href="http://wiresareobsolete.com/word$p$pss/2010/11/android-bluetooth-rfcomm/">http://wiresareobsolete.com/word$p$pss/2010/11/android-bluetooth-rfcomm/

在要点: 的UUID是必须指向发布的服务的嵌入式设备上的一个值,它不只是随机生成的。您要访问的RFCOMM SPP连接有它发布到确定服务特定的UUID,当你创建一个套接字必须相同的UUID匹配。

In gist: The UUID is a value that must point to a published service on your embedded device, it is not just randomly generated. The RFCOMM SPP connection you want to access has a specific UUID that it publishes to identify that service, and when you create a socket it must match the same UUID.

如果您的目标4.0.3设备及以上,使用 fetchUuidsWithSdp() getUuids()找所有已发布的服务和其相关的UUID值。为了向后兼容阅读文章

If you are targeting 4.0.3 device and above , use fetchUuidsWithSdp() and getUuids() to find all the published services and their associated UUID values. For backward compatibility read the article

这篇关于Android的蓝牙无法连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆