可以搜索并扫描设备但无法连接到设备并获取socket,不知道哪里的问题,求大神指点。
以下为部分代码:
寻找设备部分:
private BroadcastReceiver mReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();//服务发现远程设备时
String str = "";
if(BluetoothDevice.ACTION_FOUND.equals(action))//每扫描到一个设备,系统都会发送此广播
{
//从Intent中获取device信息
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//获取搜索到的设备信息
str = device.getName()+ ":" + device.getAddress() + "\n";
//当发现的新设备不存在于设备配对列表中时,将设备的名字和地址添加到ArrayAdapter中
if(listDevices.indexOf(str) == -1)//防止重复添加
{
listDevices.add(str);//添加搜索到的设备信息
deviceAdapter.notifyDataSetChanged();
}
}
else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
{
Toast.makeText(WindFireDemoActivity.this, "Discovery finished", Toast.LENGTH_SHORT).show();
}
}
};
listview点击事件:
text.setOnItemClickListener( new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> adapterview, View view, int position,long id)
{
// TODO Auto-generated method stub
//绑定所选择的蓝牙MAC地址设备
String str = deviceAdapter.getItem(position);
if(null == str)
{
Toast.makeText(getApplicationContext(), "未选中设备", Toast.LENGTH_SHORT).show();
}
String mac = str.substring(str.indexOf(":")+1).trim();//str.substring(str.indexOf(":")+1)取名称
device = mBluetoothAdapter.getRemoteDevice(mac);//以mac去创建一个device
new Thread(new ConnectThread()).start();
Toast.makeText(getApplicationContext(), "连接到所选设备", Toast.LENGTH_SHORT).show();
}
});
连接socket部分:
public class ConnectThread extends Thread {
public void run()
{
try{
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
Toast.makeText(WindFireDemoActivity.this, "已退出搜索,连接Socket", Toast.LENGTH_SHORT).show();
btSocket.connect();
isConnected = true;//判断语句
Toast.makeText(WindFireDemoActivity.this, "sssssssss", Toast.LENGTH_SHORT).show();
}
catch(IOException e){
e.printStackTrace();
Method m;
try {
m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
btSocket = (BluetoothSocket) m.invoke(device, 1);
btSocket.connect();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
try{
btSocket.close();
}catch (IOException ie){
Toast.makeText(WindFireDemoActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
}
}
}
}