Android 蓝牙 SPP 与 Galaxy S3

标签 android bluetooth galaxy spp

我正在尝试在运行 Android 4.0.3 的三星 Galaxy S3 和 RN 42 蓝牙芯片之间建立蓝牙连接,here是模型:

我使用了很多不同的代码来设置蓝牙串行通信,所有这些代码在我之前使用的 HTC Wildfire 上都运行良好。但是现在我使用的是galaxy s3手机,无法建立连接。这是我正在使用的代码,我找到了它 here :

我把权限放在 android list 中。

首先,我的蓝牙接口(interface):

public class BtInterface {

private BluetoothDevice device = null;
private BluetoothSocket socket = null;
private InputStream receiveStream = null;
private OutputStream sendStream = null;

private ReceiverThread receiverThread;

Handler handler;

public BtInterface(Handler hstatus, Handler h) {
    Set<BluetoothDevice> setpairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
    BluetoothDevice[] pairedDevices = (BluetoothDevice[]) setpairedDevices.toArray(new BluetoothDevice[setpairedDevices.size()]);

    for(int i=0;i<pairedDevices.length;i++) {
        if(pairedDevices[i].getName().contains("MyBluetoothChip")) {
            device = pairedDevices[i];
            try {
                socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
                receiveStream = socket.getInputStream();
                sendStream = socket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        }
    }

    handler = hstatus;

    receiverThread = new ReceiverThread(h);
}

public void sendData(String data) {
    sendData(data, false);
}

public void sendData(String data, boolean deleteScheduledData) {
    try {
        sendStream.write(data.getBytes());
        sendStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void connect() {
    new Thread() {
        @Override public void run() {
            try {
                socket.connect();

                Message msg = handler.obtainMessage();
                msg.arg1 = 1;
                handler.sendMessage(msg);

                receiverThread.start();

            } catch (IOException e) {
                Log.v("N", "Connection Failed : "+e.getMessage());
                e.printStackTrace();
            }
        }
    }.start();
}

public void close() {
    try {
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public BluetoothDevice getDevice() {
    return device;
}

private class ReceiverThread extends Thread {
    Handler handler;

    ReceiverThread(Handler h) {
        handler = h;
    }

    @Override public void run() {
        while(true) {
            try {
                if(receiveStream.available() > 0) {

                    byte buffer[] = new byte[100];
                    int k = receiveStream.read(buffer, 0, 100);

                    if(k > 0) {
                        byte rawdata[] = new byte[k];
                        for(int i=0;i<k;i++)
                            rawdata[i] = buffer[i];

                        String data = new String(rawdata);

                        Message msg = handler.obtainMessage();
                        Bundle b = new Bundle();
                        b.putString("receivedData", data);
                        msg.setData(b);
                        handler.sendMessage(msg);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
}

然后,我的主要 Activity ,只需一个连接按钮和聊天:

public class MonApp extends Activity implements OnClickListener {

private TextView logview;
private EditText sendtext;
private Button connect, send;

private BtInterface bt = null;

private long lastTime = 0;

final Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        String data = msg.getData().getString("receivedData");

        long t = System.currentTimeMillis();
        if(t-lastTime > 100) {// Pour Èviter que les messages soit coupÈs
            logview.append("\n");
            lastTime = System.currentTimeMillis();
        }
        logview.append(data);
    }
};

final Handler handlerStatus = new Handler() {
    public void handleMessage(Message msg) {
        int co = msg.arg1;
        if(co == 1) {
            logview.append("Connected\n");
        } else if(co == 2) {
            logview.append("Disconnected\n");
        }
    }
};

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

    bt = new BtInterface(handlerStatus, handler);

    logview = (TextView)findViewById(R.id.logview);
    sendtext = (EditText)findViewById(R.id.sendtxt);

    connect = (Button)findViewById(R.id.connect);
    connect.setOnClickListener(this);

    send = (Button)findViewById(R.id.send);
    send.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    if(v == connect) {
        bt.connect();
    } else if(v == send) {
        bt.sendData(sendtext.getText().toString());
    }
}
}

当我尝试连接到芯片时,这是我从 logcat 得到的:

09-05 11:37:05.515: I/BluetoothPolicyService(2097): getBluetoothDataTransferAllowed 
09-05 11:37:05.520: D/BluetoothPolicyService(2097): MDM: isProfileEnabled = true
09-05 11:37:05.520: D/BluetoothUtils(6868): isSocketAllowedBySecurityPolicy start : device null
09-05 11:37:05.525: V/BluetoothService.cpp(2097): createDeviceNative
09-05 11:37:05.525: V/BluetoothService.cpp(2097): createDeviceNative
09-05 11:37:05.525: V/BluetoothEventLoop.cpp(2097): onCreateDeviceResult
09-05 11:37:05.525: V/BluetoothEventLoop.cpp(2097): onCreateDeviceResult
09-05 11:37:05.525: E/BluetoothEventLoop.cpp(2097): onCreateDeviceResult: D-Bus error: org.bluez.Error.AlreadyExists (Already Exists)
09-05 11:37:05.525: V/BluetoothService.cpp(2097): discoverServicesNative
09-05 11:37:05.525: V/BluetoothService.cpp(2097): ... Object Path = /org/bluez/3094/hci0/dev_00_06_66_43_A1_E6
09-05 11:37:05.525: V/BluetoothService.cpp(2097): ... Pattern = , strlen = 0
09-05 11:37:10.660: V/BluetoothEventLoop.cpp(2097): onDiscoverServicesResult
09-05 11:37:10.660: V/BluetoothEventLoop.cpp(2097): ... Device Path = /org/bluez/3094/hci0/dev_00_06_66_43_A1_E6
09-05 11:37:10.660: E/BluetoothEventLoop.cpp(2097): onDiscoverServicesResult: D-Bus error: org.bluez.Error.ConnectionAttemptFailed (Host is down)
09-05 11:37:10.670: V/N(6868): Connection Failed : Service discovery failed
09-05 11:37:10.670: W/System.err(6868): java.io.IOException: Service discovery failed
09-05 11:37:10.675: W/System.err(6868):     at android.bluetooth.BluetoothSocket$SdpHelper.doSdp(BluetoothSocket.java:462)
09-05 11:37:10.675: W/System.err(6868):     at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:240)
09-05 11:37:10.675: W/System.err(6868):     at com.example.bluetooth.BtInterface$1.run(BtInterface.java:68)

我不明白为什么这段代码不适用于 galaxy s3。我试图在谷歌上搜索蓝牙兼容性问题,但到目前为止我没有找到任何东西。

谢谢!

纪尧姆

最佳答案

新的 Android ICS 存在很多蓝牙不兼容问题。显然他们乱用蓝牙代码来“提高安全性”。

A bug我发现并报告(这使得我的整个嵌入式板在一周内无法与任何 Android ICS 设备连接)是在与已经配对的设备建立连接时,Android ICS 需要重新验证——有或没有 PIN 取决于是否你用Bluetooth SSP (我使用它 - 这意味着对我来说,在 Android ICS 上,仍然可以在没有用户交互的情况下连接 2 个绑定(bind)设备 - 但需要更长的时间)。

Please vote this bug on Google Bugtracker - maybe someone will fix it...

也许这也是您的问题?您能否准确指定您的代码在哪一行中断? 用 try/catch 等包围你所有的蓝牙系统代码。

无论如何,新的蓝牙行为非常非常糟糕,我听说很多人因此无法连接到他们的旧耳机。

关于Android 蓝牙 SPP 与 Galaxy S3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12274210/

相关文章:

android - 使用 ImageView 在 PageRow 元素之间导航

android - 小部件图标下方的 Android AppWidget 标题

Android:Activity A -> C,但 C -> B -> A 通过后退按钮,该怎么做?

linux - 以下命令的作用是什么?

ios - Red Bear Lab BLE Shield 无法连接到我的 iPhone

java - 应用程序在 Android Studio 中崩溃。 getMenuInflater().inflate(R.menu.activity_main, 菜单);不存在?

ios - 如何从 iOS 网络应用程序与蓝牙设备配对?

html - 在三星浏览器中禁用选择选项文本的截断?

android - 在三星 Galaxy Ace 2.2.1 和 Galaxy Tab 中打开/关闭相机 LED/闪光灯

android - 三星 Galaxy S3 上的蓝牙 4.0/智能/低功耗