我设法创建一个ListView,搜索设备并显示它们,点击连接到所选设备,但现在我想知道如何从一部手机发送到另一部手机只是一个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());
}
}
它运作良好,两个设备都配对。
我是否需要客户端和服务器来传输内容?
答案 0 :(得分:1)
以下是android SDK的一些示例代码:BluetoothChat
关键是在连接的两端使用Service,它们都会侦听传入的消息并发送传出的消息。然后,您所有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);
}