我在Android中遇到蓝牙串行连接问题。有两个场景:
一个Activity(带片段),一个EditTex和一个Button(片段中)。该按钮与串行设备建立连接并从EditText发送数据。这是工作,但是...我不想每次建立连接。
一个Activity(带片段),一个EditTex和两个Button(片段中)。一个按钮建立连接而另一个按钮发送数据,好吧,当我按下连接按钮时它似乎工作正常(没有例外)但是当我按下发送数据按钮时,logcat显示我:
“java.io.IOException
:传输端点未连接”
当然,数据不会到达接收方。抛出
是个例外out.write(txtData.getText().toString().getBytes());
我的代码是(我想要的第二个风景):
public class MainFragment extends Fragment implements View.OnClickListener {
private EditText txtData;
private Button btnSend;
private Button btnConnect;
private InputStream in = null;
private byte[] buffer = null;
BluetoothSocket socket = null;
OutputStream out = null;
public MainFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
txtData = (EditText) rootView.findViewById(R.id.txtData);
btnSend = (Button) rootView.findViewById(R.id.btnSend);
btnConnect = (Button) rootView.findViewById(R.id.btnConnect);
btnConnect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
connectBluetooth();
}
});
btnSend.setOnClickListener(this);
return rootView;
}
public void connectBluetooth(){
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null) {
// Device does not support Bluetooth
getActivity().finish(); //exit
}
if (!adapter.isEnabled()) {
//make sure the device's bluetooth is enabled
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
final UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //UUID for serial connection
String mac = "00:1B:35:0B:75:BE"; //my device's mac adress
BluetoothDevice device = adapter.getRemoteDevice(mac); //get remote device by mac, we assume these two devices are already paired
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
socket = device.createRfcommSocketToServiceRecord(SERIAL_UUID);
} catch (IOException e) {
Log.d("socket","Error al crear el socket");
}
try {
socket.connect();
out = socket.getOutputStream();
in = socket.getInputStream();
out.write(txtData.getText().toString().getBytes());
} catch (IOException e) {
}
}
@Override
public void onClick(View view) {
try {
out.write(txtData.getText().toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
编辑:这不是其他蓝牙设备的问题,因为我在谷歌播放中使用应用程序对其进行了测试,但它确实有效。
答案 0 :(得分:1)
在发送数据之前,您确定这两台设备是否已连接?
此外,您应该在不在主线程上的单独线程中进行所有蓝牙连接。
答案 1 :(得分:1)
最后,我使用createInsecureRfcommSocketToServiceRecord(SERIAL_UUID)
代替createRfcommSocketToServiceRecord(SERIAL_UUID)