在 android 2.1 中连接到配对的蓝牙设备 (BluetoothSocket)
我正在尝试连接到配对的蓝牙设备(baracoda d-fly 条形码阅读器)。我尝试了市场上的程序GetBlueDemo
,它成功地从其套接字中读取数据。
我编写了自己的概念证明,但当我尝试连接到设备时,我总是收到异常消息。
08-23 14:39:28.635: DEBUG/BluetoothTest(19238): Could not connect to socket
08-23 14:39:28.635: DEBUG/BluetoothTest(19238): java.io.IOException: socket failed to connect
08-23 14:39:28.635: DEBUG/BluetoothTest(19238): at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:255)
08-23 14:39:28.635: DEBUG/BluetoothTest(19238): at org.me.barcodetest.MainActivity$ConnectRunnable.run(MainActivity.java:211)
08-23 14:39:28.635: DEBUG/BluetoothTest(19238): at java.lang.Thread.run(Thread.java:1102)
关于我做错了什么有什么建议吗?
package org.me.barcodetest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 2;
private BluetoothAdapter bluetoothAdapter;
private UUID applicationUUID = java.util.UUID.randomUUID();
private static final String logTag = "BluetoothTest";
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Log.d(logTag, "Could not get bluetooth adapter");
return;
}
searchForDevices();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BT) {
if (requestCode == RESULT_OK) {
Log.d("BluetoothTest", "bluetooth enabled");
searchForDevices();
} else {
Log.d("BluetoothTest", "Could not enable bluetooth device");
}
}
}
public void lineReadFromBluetoothDevice(String line) {
Log.d(logTag, "Mottok: " + line);
}
private void searchForDevices() {
if (bluetoothAdapter.isEnabled()) {
Set<BluetoothDevice> devicesAvailable = bluetoothAdapter.getBondedDevices();
if (devicesAvailable.isEmpty()) {
informUserNoDevicesPaired();
} else {
askUserToPickDeviceToUse(devicesAvailable);
}
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
private void askUserToPickDeviceToUse(Set<BluetoothDevice> devicesAvailable) {
final ListView view = new ListView(this);
view.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
ArrayAdapter<BluetoothDevice> adapter =
new ArrayAdapter(this, R.layout.devicesavailabletextview, devicesAvailable.toArray(new BluetoothDevice[devicesAvailable.size()])) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView) super.getView(position, convertView, parent);
BluetoothDevice bluetoothDevice = (BluetoothDevice) getItem(position);
view.setText(bluetoothDevice.getName() + " : " + bluetoothDevice.getAddress());
return view;
}
};
view.setAdapter(adapter);
view.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
pairToDevice((BluetoothDevice) view.getItemAtPosition(position));
}
});
Dialog dialog = new Dialog(this);
dialog.setContentView(view);
dialog.setCancelable(true);
dialog.show();
}
private void informUserNoDevicesPaired() {
Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setMessage("Ingen \"Paired\" enheter");
dialogBuilder.setPositiveButton("Søk", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
}
});
dialogBuilder.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
dialog.dismiss();
finish();
}
});
dialogBuilder.show();
}
private void showError(String message) {
Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setMessage("Det oppstod en feil i programmet:\n\n" + message);
dialogBuilder.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
dialog.dismiss();
finish();
}
});
dialogBuilder.show();
}
private void pairToDevice(BluetoothDevice bluetoothDevice) {
openSocket(bluetoothDevice);
}
private void openSocket(BluetoothDevice bluetoothDevice) {
try {
final ProgressDialog dialog = new ProgressDialog(this);
final ConnectRunnable connector = new ConnectRunnable(bluetoothDevice, dialog);
dialog.show(this, "Kobler til", "Koblier til " + bluetoothDevice.getName() + " : " + bluetoothDevice.getAddress(),
true, true,
new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
connector.cancel();
}
});
new Thread(connector).start();
} catch (IOException ex) {
Log.d(logTag, "Could not open bluetooth socket", ex);
showError("Kunne ikke åpne socket grunnet feil: " + ex.getMessage());
}
}
private void closeSocket(BluetoothSocket openSocket) {
try {
openSocket.close();
} catch (IOException ex) {
Log.d(logTag, "Could not close exisiting socket", ex);
}
}
private void startListeningForInput(BluetoothSocket socket) {
new Thread(new InputReader(socket)).start();
}
private void dismissDialog(final Dialog dialog) {
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
private class ConnectRunnable implements Runnable {
private final ProgressDialog dialog;
private final BluetoothSocket socket;
public ConnectRunnable(BluetoothDevice device, ProgressDialog dialog) throws IOException {
socket = device.createRfcommSocketToServiceRecord(applicationUUID);
this.dialog = dialog;
}
public void run() {
try {
bluetoothAdapter.cancelDiscovery();
socket.connect();
} catch (IOException connectException) {
Log.d(logTag, "Could not connect to socket", connectException);
closeSocket(socket);
return;
}
startListeningForInput(socket);
dismissDialog(dialog);
}
public void cancel() {
try {
socket.close();
} catch (IOException e) {
Log.d(logTag, "Canceled connection", e);
}
}
}
private class InputReader implements Runnable {
private final BluetoothSocket socket;
public InputReader(BluetoothSocket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
final InputStream input = socket.getInputStream();
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
String line;
while ((line = bufferedReader.readLine()) != null) {
lineReadFromBluetoothDevice(line);
}
} catch (IOException ex) {
showError("Mistet forbindelsen: " + ex.getMessage());
}
}
public void cancel() {
try {
socket.close();
} catch (IOException e) {
}
}
}
}
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
设备可用文本视图:
<?xml version="1.0" encoding="UTF-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
I am trying to connect to a paired bluetooth
device (baracoda d-fly bar code reader). I tried the program GetBlueDemo
from market and this manages to read from its socket.
I wrote my own proof of concept, but i just keep getting an excpetion when i try to connect to the device.
08-23 14:39:28.635: DEBUG/BluetoothTest(19238): Could not connect to socket
08-23 14:39:28.635: DEBUG/BluetoothTest(19238): java.io.IOException: socket failed to connect
08-23 14:39:28.635: DEBUG/BluetoothTest(19238): at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:255)
08-23 14:39:28.635: DEBUG/BluetoothTest(19238): at org.me.barcodetest.MainActivity$ConnectRunnable.run(MainActivity.java:211)
08-23 14:39:28.635: DEBUG/BluetoothTest(19238): at java.lang.Thread.run(Thread.java:1102)
Any suggestions on what i am doing wrong?
package org.me.barcodetest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 2;
private BluetoothAdapter bluetoothAdapter;
private UUID applicationUUID = java.util.UUID.randomUUID();
private static final String logTag = "BluetoothTest";
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Log.d(logTag, "Could not get bluetooth adapter");
return;
}
searchForDevices();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BT) {
if (requestCode == RESULT_OK) {
Log.d("BluetoothTest", "bluetooth enabled");
searchForDevices();
} else {
Log.d("BluetoothTest", "Could not enable bluetooth device");
}
}
}
public void lineReadFromBluetoothDevice(String line) {
Log.d(logTag, "Mottok: " + line);
}
private void searchForDevices() {
if (bluetoothAdapter.isEnabled()) {
Set<BluetoothDevice> devicesAvailable = bluetoothAdapter.getBondedDevices();
if (devicesAvailable.isEmpty()) {
informUserNoDevicesPaired();
} else {
askUserToPickDeviceToUse(devicesAvailable);
}
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
private void askUserToPickDeviceToUse(Set<BluetoothDevice> devicesAvailable) {
final ListView view = new ListView(this);
view.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
ArrayAdapter<BluetoothDevice> adapter =
new ArrayAdapter(this, R.layout.devicesavailabletextview, devicesAvailable.toArray(new BluetoothDevice[devicesAvailable.size()])) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView) super.getView(position, convertView, parent);
BluetoothDevice bluetoothDevice = (BluetoothDevice) getItem(position);
view.setText(bluetoothDevice.getName() + " : " + bluetoothDevice.getAddress());
return view;
}
};
view.setAdapter(adapter);
view.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
pairToDevice((BluetoothDevice) view.getItemAtPosition(position));
}
});
Dialog dialog = new Dialog(this);
dialog.setContentView(view);
dialog.setCancelable(true);
dialog.show();
}
private void informUserNoDevicesPaired() {
Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setMessage("Ingen \"Paired\" enheter");
dialogBuilder.setPositiveButton("Søk", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
}
});
dialogBuilder.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
dialog.dismiss();
finish();
}
});
dialogBuilder.show();
}
private void showError(String message) {
Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setMessage("Det oppstod en feil i programmet:\n\n" + message);
dialogBuilder.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
dialog.dismiss();
finish();
}
});
dialogBuilder.show();
}
private void pairToDevice(BluetoothDevice bluetoothDevice) {
openSocket(bluetoothDevice);
}
private void openSocket(BluetoothDevice bluetoothDevice) {
try {
final ProgressDialog dialog = new ProgressDialog(this);
final ConnectRunnable connector = new ConnectRunnable(bluetoothDevice, dialog);
dialog.show(this, "Kobler til", "Koblier til " + bluetoothDevice.getName() + " : " + bluetoothDevice.getAddress(),
true, true,
new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
connector.cancel();
}
});
new Thread(connector).start();
} catch (IOException ex) {
Log.d(logTag, "Could not open bluetooth socket", ex);
showError("Kunne ikke åpne socket grunnet feil: " + ex.getMessage());
}
}
private void closeSocket(BluetoothSocket openSocket) {
try {
openSocket.close();
} catch (IOException ex) {
Log.d(logTag, "Could not close exisiting socket", ex);
}
}
private void startListeningForInput(BluetoothSocket socket) {
new Thread(new InputReader(socket)).start();
}
private void dismissDialog(final Dialog dialog) {
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
private class ConnectRunnable implements Runnable {
private final ProgressDialog dialog;
private final BluetoothSocket socket;
public ConnectRunnable(BluetoothDevice device, ProgressDialog dialog) throws IOException {
socket = device.createRfcommSocketToServiceRecord(applicationUUID);
this.dialog = dialog;
}
public void run() {
try {
bluetoothAdapter.cancelDiscovery();
socket.connect();
} catch (IOException connectException) {
Log.d(logTag, "Could not connect to socket", connectException);
closeSocket(socket);
return;
}
startListeningForInput(socket);
dismissDialog(dialog);
}
public void cancel() {
try {
socket.close();
} catch (IOException e) {
Log.d(logTag, "Canceled connection", e);
}
}
}
private class InputReader implements Runnable {
private final BluetoothSocket socket;
public InputReader(BluetoothSocket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
final InputStream input = socket.getInputStream();
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
String line;
while ((line = bufferedReader.readLine()) != null) {
lineReadFromBluetoothDevice(line);
}
} catch (IOException ex) {
showError("Mistet forbindelsen: " + ex.getMessage());
}
}
public void cancel() {
try {
socket.close();
} catch (IOException e) {
}
}
}
}
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
devicesavailabletextview:
<?xml version="1.0" encoding="UTF-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是我的uuid,我认为这只是一个让android知道它来自哪里的uuid,但它必须是“00001101-0000-1000-8000-00805F9B34FB”
The problem was my uuid, i figured this was just an uuid for android to know where it came from, but it had to be "00001101-0000-1000-8000-00805F9B34FB"
条形码扫描仪使用 SPP 协议 - 因此您必须使用 SPP UUID 才能连接到它。
The barcode scanner uses the SPP protocol - so your have to use the SPP UUID to connect to it.