Android SPP Socket createRfcommSocketToServiceRecord 不会连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2519449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:09:54  来源:igfitidea点击:

SPP Socket createRfcommSocketToServiceRecord will not connect

androidbluetoothrfcomm

提问by philDev

I want to use Android 2.1 to connect to an external Bluetooth device, wich is offering an SPP port to me. In this case it is an external GPS unit. When I'm trying to connect I can't connect an established socket while being in the "client" mode. Then if I try to set up a socket (being in the server role), to RECEIVE text from my PC everything works just fine. The Computer can connect as the client to the Socket on the Phone via SPP using the SSP UUID or some random UUID. So the Problem is not that I'm using the wrong UUID.

我想使用 Android 2.1 连接到外部蓝牙设备,它为我提供了一个 SPP 端口。在这种情况下,它是一个外部 GPS 单元。当我尝试连接时,处于“客户端”模式时无法连接已建立的套接字。然后,如果我尝试设置一个套接字(处于服务器角色),从我的 PC 接收文本一切正常。计算机可以作为客户端使用 SSP UUID 或一些随机 UUID 通过 SPP 连接到电话上的套接字。所以问题不在于我使用了错误的 UUID。

But the other way around (e.g. calling connect on the established client socket) createRfcommSocketToServiceRecord(UUID uuid)) just doesn't work. Sadly I don't have the time to inspect the problem further. It would be greate If somebody could point me the right way. Phone: Samsung Galaxy Spica I-5700 Android 2.1 In the following part of the Logfile has to be the Problem.

但反过来(例如,在已建立的客户端套接字上调用 connect createRfcommSocketToServiceRecord(UUID uuid))就行不通了。可悲的是,我没有时间进一步检查问题。如果有人能指出我正确的方向,那就太好了。电话:Samsung Galaxy Spica I-5700 Android 2.1 在日志文件的以下部分必须是问题。

Greets PhilDev

问候 PhilDev

P.S. I'm going to be present during the Office hours.

PS 我将在办公时间出席。

Here the log file:

这里的日志文件:



03-21 03:10:52.020: DEBUG/BluetoothSocket.cpp(4643): initSocketFromFdNative
03-21 03:10:52.025: DEBUG/BluetoothSocket(4643): connect
03-21 03:10:52.025: DEBUG/BluetoothSocket(4643): doSdp
03-21 03:10:52.050: DEBUG/ADAPTER(2132): create_device(01:00:00:7F:B5:B3)
03-21 03:10:52.050: DEBUG/ADAPTER(2132): adapter_create_device(01:00:00:7F:B5:B3)
03-21 03:10:52.055: DEBUG/DEVICE(2132): Creating device [address = 01:00:00:7F:B5:B3] /org/bluez/2132/hci0/dev_01_00_00_7F_B5_B3 [name = ]
03-21 03:10:52.055: DEBUG/DEVICE(2132): btd_device_ref(0x10c18): ref=1
03-21 03:10:52.065: INFO/BluetoothEventLoop.cpp(1914): event_filter: Received signal org.bluez.Adapter:DeviceCreated from /org/bluez/2132/hci0
03-21 03:10:52.065: INFO/BluetoothService.cpp(1914): ... Object Path = /org/bluez/2132/hci0/dev_01_00_00_7F_B5_B3
03-21 03:10:52.065: INFO/BluetoothService.cpp(1914): ... Pattern = 00001101-0000-1000-8000-00805f9b34fb, strlen = 36
03-21 03:10:52.070: DEBUG/DEVICE(2132): *************DiscoverServices********
03-21 03:10:52.070: INFO/DTUN_HCID(2132): dtun_client_get_remote_svc_channel: starting discovery on  (uuid16=0x0011)
03-21 03:10:52.070: INFO/DTUN_HCID(2132):    bdaddr=01:00:00:7F:B5:B3
03-21 03:10:52.070: INFO/DTUN_CLNT(2132):     Client calling DTUN_METHOD_DM_GET_REMOTE_SERVICE_CHANNEL (id 4)
03-21 03:10:52.070: INFO/(2106): DTUN_ReceiveCtrlMsg: [DTUN] Received message [BTLIF_DTUN_METHOD_CALL] 4354
03-21 03:10:52.070: INFO/(2106): handle_method_call: handle_method_call :: received DTUN_METHOD_DM_GET_REMOTE_SERVICE_CHANNEL (id 4), len 134
03-21 03:10:52.075: ERROR/BTLD(2106): ****************search UUID = 1101***********
03-21 03:10:52.075: INFO//system/bin/btld(2103):         btapp_dm_GetRemoteServiceChannel()
03-21 03:10:52.120: DEBUG/BluetoothService(1914): updateDeviceServiceChannelCache(01:00:00:7F:B5:B3)
03-21 03:10:52.120: DEBUG/BluetoothEventLoop(1914): ClassValue: null for remote device: 01:00:00:7F:B5:B3 is null
03-21 03:10:52.120: INFO/BluetoothEventLoop.cpp(1914): event_filter: Received signal org.bluez.Adapter:PropertyChanged from /org/bluez/2132/hci0
03-21 03:10:52.305: WARN/BTLD(2106): bta_dm_check_av:0
03-21 03:10:56.395: DEBUG/WifiService(1914): ACTION_BATTERY_CHANGED pluggedType: 2
03-21 03:10:57.440: WARN/BTLD(2106): SDP - Rcvd conn cnf with error: 0x4  CID 0x43
03-21 03:10:57.440: INFO/BTL-IFS(2106): send_ctrl_msg: [BTL_IFS CTRL] send BTLIF_DTUN_SIGNAL_EVT (CTRL) 13 pbytes (hdl 10)
03-21 03:10:57.445: INFO/DTUN_CLNT(2132): dtun-rx signal [DTUN_SIG_DM_RMT_SERVICE_CHANNEL] (id 42) len 15
03-21 03:10:57.445: INFO/DTUN_HCID(2132): dtun_dm_sig_rmt_service_channel: success=1, service=00000000
03-21 03:10:57.445: ERROR/DTUN_HCID(2132): discovery unsuccessful!


package de.phil_dev.android.BT;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class ThinBTClient extends Activity {

    private static final String TAG = "THINBTCLIENT";
    private static final boolean D = true;
    private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothSocket btSocket = null;
    private BufferedInputStream inStream = null;
    private BluetoothServerSocket myServerSocket;
    private ConnectThread myConnection;
    private ServerThread myServer;
    // Well known SPP UUID (will *probably* map to
    // RFCOMM channel 1 (default) if not in use);
    // see comments in onResume().
    private static final UUID MY_UUID = UUID
            .fromString("00001101-0000-1000-8000-00805F9B34FB");


    // .fromString("94f39d29-7d6d-437d-973b-fba39e49d4ee");

    // ==> hardcode your slaves MAC address here <==
    // PC
    // private static String address = "00:09:DD:50:86:A0";

    // GPS
    private static String address = "00:0B:0D:8E:D4:33";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        if (D)
            Log.e(TAG, "+++ ON CREATE +++");

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available.",
                    Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        if (!mBluetoothAdapter.isEnabled()) {
            Toast.makeText(this,
                    "Please enable your BT and re-run this program.",
                    Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        if (D)
            Log.e(TAG, "+++ DONE IN ON CREATE, GOT LOCAL BT ADAPTER +++");
    }

    @Override
    public void onStart() {
        super.onStart();
        if (D)
            Log.e(TAG, "++ ON START ++");
    }

    @Override
    public void onResume() {
        super.onResume();

        if (D) {
            Log.e(TAG, "+ ON RESUME +");
            Log.e(TAG, "+ ABOUT TO ATTEMPT CLIENT CONNECT +");
        }

        // Make the phone discoverable

        // When this returns, it will 'know' about the server,
        // via it's MAC address.
        // mBluetoothAdapter.startDiscovery();
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        Log.e(TAG, device.getName() + " connected");


//       myServer = new ServerThread();
//       myServer.start();

        myConnection = new ConnectThread(device);
        myConnection.start();

    }

    @Override
    public void onPause() {
        super.onPause();

        if (D)
            Log.e(TAG, "- ON PAUSE -");

        try {
            btSocket.close();
        } catch (IOException e2) {
            Log.e(TAG, "ON PAUSE: Unable to close socket.", e2);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (D)
            Log.e(TAG, "-- ON STOP --");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (D)
            Log.e(TAG, "--- ON DESTROY ---");
    }

    private class ServerThread extends Thread {
        private final BluetoothServerSocket myServSocket;

        public ServerThread() {
            BluetoothServerSocket tmp = null;

            // create listening socket
            try {
                tmp = mBluetoothAdapter
                        .listenUsingRfcommWithServiceRecord(
                                "myServer", MY_UUID);
            } catch (IOException e) {
                Log.e(TAG, "Server establishing failed");
            }

            myServSocket = tmp;
        }

        public void run() {
            Log.e(TAG, "Beginn waiting for connection");
            BluetoothSocket connectSocket = null;

            InputStream inStream = null;
            byte[] buffer = new byte[1024];
            int bytes;

            while (true) {
                try {
                    connectSocket = myServSocket.accept();
                } catch (IOException e) {
                    Log.e(TAG, "Connection failed");
                    break;
                }

                Log.e(TAG, "ALL THE WAY AROUND");
                try {
                    connectSocket = connectSocket.getRemoteDevice()
                            .createRfcommSocketToServiceRecord(MY_UUID);
                    connectSocket.connect();
                } catch (IOException e1) {
                    Log.e(TAG, "DIDNT WORK");
                }

                // handle Connection
                try {
                    inStream = connectSocket.getInputStream();
                    while (true) {
                        try {
                            bytes = inStream.read(buffer);
                            Log.e(TAG, "Received: " + buffer.toString());
                        } catch (IOException e3) {
                            Log.e(TAG, "disconnected");
                            break;
                        }
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    break;
                }

            }
        }

        void cancel() {

        }
    }

    private class ConnectThread extends Thread {

        private final BluetoothSocket mySocket;
        private final BluetoothDevice myDevice;

        public ConnectThread(BluetoothDevice device) {
            myDevice = device;
            BluetoothSocket tmp = null;

            try {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
                Log.e(TAG, "CONNECTION IN THREAD DIDNT WORK");
            }
            mySocket = tmp;
        }

        public void run() {
            Log.e(TAG, "STARTING TO CONNECT THE SOCKET");
            setName("My Connection Thread");
            InputStream inStream = null;
            boolean run = false;
            //mBluetoothAdapter.cancelDiscovery();

            try {
                mySocket.connect();
                run = true;
            } catch (IOException e) {
                run = false;
                Log.e(TAG, this.getName()
                        + ": CONN DIDNT WORK, Try closing socket");
                try {
                    mySocket.close();
                } catch (IOException e1) {
                    Log.e(TAG, this.getName() + ": COULD CLOSE SOCKET", e1);

                    this.destroy();
                }
            }

            synchronized (ThinBTClient.this) {
                myConnection = null;
            }

            byte[] buffer = new byte[1024];
            int bytes;
            // handle Connection
            try {
                inStream = mySocket.getInputStream();
                while (run) {

                    try {
                        bytes = inStream.read(buffer);
                        Log.e(TAG, "Received: " + buffer.toString());
                    } catch (IOException e3) {
                        Log.e(TAG, "disconnected");
                    }
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // starting connected thread (handling there in and output
        }

        public void cancel() {
            try {
                mySocket.close();
            } catch (IOException e) {
                Log.e(TAG, this.getName() + " SOCKET NOT CLOSED");
            }
        }

    }

}


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.phil_dev.android.BT" android:versionCode="1"
    android:versionName="1.0">
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">
        <activity android:name=".ThinBTClient" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="7" />

</manifest> 

回答by Luis

I found this exact problem happens when one of the devices has the Bluetooth turned off.

我发现当其中一台设备关闭蓝牙时会发生这个确切的问题。

回答by Brad Hein

I'm having a similar problem on HTC Droid.

我在 HTC Droid 上遇到了类似的问题。

Mine gets a tiny bit further though and connect()succeeds but I am unable to receive so much as a single byte on the socket InputStream.

我的虽然更进一步并connect()成功了,但我无法在套接字上接收到单个字节InputStream

Why can't HTC Droid running OTA 2.1 communicate with RFCOMM?

为什么运行 OTA 2.1 的 HTC Droid 无法与 RFCOMM 通信?

I think we've hit a limitation in the way HTC has implemented Bluetooth on their phones. Note that the manufacturers, such as HTC, have to write drivers so that Android OS can communicate with their proprietary hardware. HTC seems to have released 2.0/2.1 without complete driver support.

我认为我们在 HTC 在他们的手机上实现蓝牙的方式上遇到了限制。请注意,制造商(例如 HTC)必须编写驱动程序,以便 Android 操作系统可以与其专有硬件进行通信。HTC 似乎发布了没有完整驱动程序支持的 2.0/2.1。