发送一个 int 到配对的蓝牙设备

Send an int to a paired Bluetooth device

我设法创建了一个 ListView,搜索设备并显示它们,点击连接到所选设备,但现在我想知道如何从一个 phone 发送到另一个只是一个 int或布尔值或类似的东西。
这是一个小游戏,有赢家和输家 - 所以我想比较两个变量并检查谁赢了,然后显示它。

到目前为止我的代码:

正在搜索

bluetooth.startDiscovery();
  textview.setText("Searching, Make sure other device is available");
  IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
  registerReceiver(mReceiver, filter);

在 ListView 中显示

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            device = intent
                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            mDeviceList.add(device.getName() + "\n" + device.getAddress());
            Log.i("BT", device.getName() + "\n" + device.getAddress());
            listView.setAdapter(new ArrayAdapter<String>(context,
                    android.R.layout.simple_list_item_1, mDeviceList));
        }
    }
};
      @Override
protected void onDestroy() {
    unregisterReceiver(mReceiver);
    super.onDestroy();
}

正在配对设备

    private void pairDevice(BluetoothDevice device) {
    try {
        Log.d("pairDevice()", "Start Pairing...");
        Method m = device.getClass().getMethod("createBond", (Class[]) null);
        m.invoke(device, (Object[]) null);
        Log.d("pairDevice()", "Pairing finished.");
    } catch (Exception e) {
        Log.e("pairDevice()", e.getMessage());
    }
}

效果很好,两个设备都已配对。
我需要客户端和服务器来传输整数吗?

这是 android SDK 中的一些示例代码:BluetoothChat

关键是使用 Service on both sides of the connection that both listens for incoming messages and sends outgoing messages. Then all your Activity 必须担心与用户交互,并告诉服务发送适当的消息。

//METHOD FROM ACTIVITY
private void sendMessage(String message) {
    // Check that we're actually connected before trying anything
    if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
        Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
        return;
    }
    // Check that there's actually something to send
    if (message.length() > 0) {
        // Get the message bytes and tell the BluetoothChatService to write
        byte[] send = message.getBytes();
        mChatService.write(send);
        // Reset out string buffer to zero and clear the edit text field
        mOutStringBuffer.setLength(0);
        mOutEditText.setText(mOutStringBuffer);
    }
}

//METHOD FROM SERVICE
public void write(byte[] out) {
    // Create temporary object
    ConnectedThread r;
    // Synchronize a copy of the ConnectedThread
    synchronized (this) {
        if (mState != STATE_CONNECTED) return;
        r = mConnectedThread;
    }
    // Perform the write unsynchronized
    r.write(out);
}