安卓蓝牙 : Unable to connect to listening socket after generating a random UUID

标签 android sockets bluetooth device serversocket

我的程序有两个不同的实例未连接到 BluetoothServerSocket

在使用 SCAN_MODE_CONNECTABLE_DISCOVERABLE 启动扫描模式之前,其中一个实例只有 1 个随机生成的 UUID,然后使用生成的相同 UUID 创建一个 BluetoothServerSocket 以进行监听。另一个实例在 BluetoothDevice 尝试连接刚刚生成的 UUID 之前生成一个随机 UUID。

每个实例都无法完成蓝牙连接。整个程序,我放了很多Log,就是想看看为什么会连不上。

下面是第一个实例的代码。 (在应用程序启动时生成 1 个随机 UUID。)如果有人想下载我的 Eclipse 项目看看,here's the link of the project from MediaFire.至于第二种情况,取消注释下面代码中的 C 风格注释将显示它。

我预计结果会在两个设备之间成功连接。成功的连接使用生成的 UUID 将设备连接到监听套接字。观察结果表明这不太可能。

据我所知,获取UUID的唯一方法是从UUID.randomUUID()获取。如果还有其他方法,请在下方留言,我会查看。但就目前而言,这不是我想要的答案。

提前致谢。

package o.p;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

/**
 * The purpose of this app is to create a server-only Bluetooth connection that
 * only accepts incoming Bluetooth connections. It is used only for testing
 * one device that needs Bluetooth tweaking in order to consistently work
 * correctly on the other device. In short, 2 devices are required.
 * */

public class Main extends Activity implements View.OnClickListener {
    //Button
    private Button acceptButton;
    private Button scanButton;

    //Bluetooth stuffs.
    private BluetoothAdapter btAdapter;
    private BluetoothServerSocket serverSocket;
    private BluetoothSocket socket;
    private BluetoothDevice targetDevice;
    private final UUID uuid = UUID.randomUUID();

    /*private UUID randomUUID;*/

    //Accepting thread.
    private class Accept implements Runnable {
        private BluetoothServerSocket socket;
        private BluetoothSocket result = null;

        public Accept(BluetoothServerSocket s) {
            socket = s;
            result = null;
        }

        @Override
        public void run() {
            try {
                Log.d("DEBUG", "Accepting.");
                result = socket.accept();
                Log.d("DEBUG", "Closing server socket.");
                socket.close();
            }
            catch (IOException e) {
                Log.d("DEBUG - onClick(), case Accept", "Unable to accept incoming connection.");
            }
        }

        public BluetoothSocket getSocket() {
            while (result == null);
            return result;
        }
    }

    //Connecting thread.
    private class Connecting implements Runnable {
        private BluetoothDevice device;

        public Connecting(BluetoothDevice d) {
            device = d;
        }

        @Override
        public void run() {
            try {


                   /*Log.d("DEBUG", "Generating a new random UUID.");
                randomUUID = UUID.randomUUID();*/
                Log.d("DEBUG", "Obtaining a socket.");
                BluetoothSocket s = device.createRfcommSocketToServiceRecord(uuid);
                Log.d("DEBUG", "Cancelling discovery, if it's still discovering.");
                if (btAdapter.isDiscovering())
                    btAdapter.cancelDiscovery();
                Log.d("DEBUG", "Connecting to listening socket with UUID: " + uuid.toString());
                s.connect();

            }
            catch (IOException e) {
                Log.d("DEBUG - Connecting.run()", "Unable to connect to the listening socket.");
            }
        }
    }

    //Thread executor
    private ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    //BroadcastReceiver for accepting Bluetooth
    private BroadcastReceiver receiver;

    @Override
    public void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.main);
        init();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_accept:
                Log.d("DEBUG", "Pressing the Accept button.");
                Accept acceptThread = new Accept(serverSocket);
                Connecting connectThread = new Connecting(targetDevice);
                if (serverSocket != null) {
                    executor.execute(acceptThread);
                    executor.execute(connectThread);
                    socket = acceptThread.getSocket();
                }
                else {
                    Log.d("DEBUG", "Server socket isn't ready.");
                    Toast.makeText(this, "Server socket isn't ready.", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.button_scan:
                if (btAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
                    Log.d("DEBUG", "Initiating discovery scan mode.");
                    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                    this.startActivity(discoverableIntent);
                    Toast.makeText(this, "Being discovered...", Toast.LENGTH_LONG).show();
                }
                if (btAdapter.isDiscovering()) {
                    Toast.makeText(this, "Re-scanning...", Toast.LENGTH_SHORT).show();
                    Log.d("DEBUG", "Re-scanning.");
                    btAdapter.cancelDiscovery();
                }
                Log.d("DEBUG", "Scanning.");
                Toast.makeText(this, "Scanning...", Toast.LENGTH_LONG).show();
                btAdapter.startDiscovery();
                break;
        }
    }

    private void init() {
        Log.d("DEBUG", "Initializing.");
        Log.d("DEBUG", "Button initializing.");
        acceptButton = (Button) findViewById(R.id.button_accept);
        acceptButton.setOnClickListener(this);
        scanButton = (Button) findViewById(R.id.button_scan);
        scanButton.setOnClickListener(this);
        Log.d("DEBUG", "Registering BroadcastReceiver.");
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    Log.d("DEBUG", "Device has been found.");
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    Log.d("DEBUG", "Obtained a device from Intent.");
                    if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                        Log.d("DEBUG", "Removing paired device.");
                        try {
                            Method m = device.getClass().getMethod("removeBond", (Class[]) null);
                            m.invoke(device, (Object[]) null);
                            Log.d("DEBUG", "Removed " + device);
                        }
                        catch (NoSuchMethodException e) {
                            Log.e("ERROR - DeviceReceiver.onReceive()", "", e);
                        }
                        catch (IllegalArgumentException e) {
                            Log.e("ERROR - DeviceReceiver.onReceive()", "", e);
                        }
                        catch (IllegalAccessException e) {
                            Log.e("ERROR - DeviceReceiver.onReceive()", "", e);
                        }
                        catch (InvocationTargetException e) {
                            Log.e("ERROR - DeviceReceiver.onReceive()", "", e);
                        }
                    }
                    else {
                        Log.d("DEBUG", "Obtaining remote device's address.");
                        btAdapter.getRemoteDevice(device.getAddress());
                        try {
                            serverSocket = btAdapter.listenUsingRfcommWithServiceRecord(device.getName(), uuid);
                            Log.d("DEBUG", "Listening to " + device.getName() + "...");
                        }
                        catch (IOException e) {
                            Log.d("DEBUG - onReceive()", "Unable to create a server socket after receiving a broadcast.", e);
                            serverSocket = null;
                            Log.d("DEBUG", "Server socket is set to null.");
                        }
                    }
                    targetDevice = device;
                }
                else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                    Log.d("DEBUG", "Scanning finished.");
                }
            }
        };
        Log.d("DEBUG", "Creating Bluetooth Adapter.");
        btAdapter = BluetoothAdapter.getDefaultAdapter();
        try {
            Log.d("DEBUG", "Creating a server socket for listening using UUID: " + uuid.toString());
            serverSocket = btAdapter.listenUsingRfcommWithServiceRecord("server", uuid);
        }
        catch (IOException e) {
            Log.d("DEBUG - init()", "Error in creating a server socket from uuid.");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //TODO: Not done with the receivers.
        IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(receiver, filter);
        filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(receiver, filter);
    }

    @Override
    public void onPause() {
        //TODO: Complete this one. Same for onResume().
        super.onPause();
        unregisterReceiver(receiver);
    }
}

最佳答案

为了能够连接 UUID 应该匹配。 在服务器端,你所做的是正确的,即生成一个随机 UUID 并监听它, 但是客户端需要使用服务器正在监听的相同 UUID 进行连接。 获取它的方法是从您的客户端使用 Server BluetoothDevice 对象上的 fetchUuidsWithSdp() 并使用获得的 UUID 连接到服务器。

关于安卓蓝牙 : Unable to connect to listening socket after generating a random UUID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14751099/

相关文章:

android - 覆盖电话标准按钮

php - 如何使用 PHP 创建到同一主机的多个持久套接字连接 TCP/IP

java - c++ 套接字客户端继续从 Java 服务器接收某些内容,即使输出流已关闭

ios - 我如何在不读取 BLE 特性的情况下知道它是否已加密?

ios - 如何在 iOS 上使用 BluetoothManager.framework 私有(private) API 发送和接收数据

android - 如何在运行时检查 android 安全权限?

android - 网络客户端安卓

java - Android蓝牙读取消息未获取消息的第一个字符

java - 将图像转换为文本形式(压缩)并在 android 中从文本转换回图像

java - Netty的ChannelOption中的SO_TIMEOUT和CONNECT_TIMEOUT_MILLIS是什么意思?