Android蓝牙连接和接收数据
我正在开发一个Android应用程序,它在其中接收配对设备的列表。我想从可用设备列表中启动与用户单击的设备的连接。因此,我向用户显示配对设备的列表,然后单击其中一个,应用程序应该开始侦听并接收来自所选设备的CSV格式的数据 我对这个问题做了很多研究,但我越来越困惑。在Android蓝牙连接和接收数据,android,bluetooth,android-bluetooth,Android,Bluetooth,Android Bluetooth,我正在开发一个Android应用程序,它在其中接收配对设备的列表。我想从可用设备列表中启动与用户单击的设备的连接。因此,我向用户显示配对设备的列表,然后单击其中一个,应用程序应该开始侦听并接收来自所选设备的CSV格式的数据 我对这个问题做了很多研究,但我越来越困惑。在onItemClickListener方法中我应该做什么才能得到我想要的 这是我的密码: public void onItemClick(AdapterView<?> parent, View view, int pos
onItemClickListener
方法中我应该做什么才能得到我想要的
这是我的密码:
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String info = ((TextView)view).getText().toString();
String address = info.substring(info.length() - 17);
BluetoothDevice device = myBluetoothAdapter.getRemoteDevice(address);
try {
Log.d("pairDevice()", "Start Pairing...");
Class cl = Class.forName("android.bluetooth.BluetoothDevice");
Class[] par = {};
Method method = cl.getMethod("createBond", par);
Object[] args = {};
method.invoke(device, args);
} catch (Exception e) {
}
BluetoothSocket tmp = null;
BluetoothSocket mmSocket = null;
final UUID uuid = UUID.fromString("fc5ffc49-00e3-4c8b-9cf1-6b72aad1001a");
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(uuid);
Method m;
try {
m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
Log.e(TAG, "create() failed", e);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mmSocket = tmp;
}
}
public void onItemClick(AdapterView父视图、视图、int位置、,
长id){
字符串信息=((TextView)视图).getText().toString();
字符串地址=信息子字符串(信息长度()-17);
BluetoothDevice=myBluetoothAdapter.getRemoteDevice(地址);
试一试{
Log.d(“pairDevice(),“开始配对…”);
Class cl=Class.forName(“安卓.蓝牙.蓝牙设备”);
类[] PAR={};
方法=cl.getMethod(“createBond”,par);
对象[]args={};
调用(设备、参数);
}捕获(例外e){
}
BluetoothSocket tmp=null;
BluetoothSocket mmSocket=null;
最终UUID UUID=UUID.fromString(“fc5ffc49-00e3-4c8b-9cf1-6b72aad1001a”);
//获取一个BluetoothSocket用于与的连接
//给定蓝牙设备
试一试{
tmp=设备.createrFComSocketToServiceRecord(uuid);
方法m;
试一试{
m=device.getClass().getMethod(“CreateRfcomSocket”,新类[]{int.Class});
tmp=(BluetoothSocket)m.invoke(设备,1);
}捕获(无此方法例外){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}捕获(IOE异常){
Log.e(标记“create()failed”,e);
}捕获(IllegalArgumentException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(非法访问例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(调用TargetException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
mmSocket=tmp;
}
}
任何帮助都将不胜感激。此链接可能会对您有所帮助