网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
//赋值给设备
mmdevice = device;
try {
Method m = mBluetoothDevice.getClass().getMethod(
"createRfcommSocket", new Class[] { int.class });
temp = (BluetoothSocket) m.invoke(mBluetoothDevice, 1);//这里端口为1
} catch(IOException e) {}
//赋值给BluetoothSocket
mmSocket = tmp;
}
public void run(){
try {
System.out.println("连接ing.....");
mmSocket.connect();
isConnect = true;
System.out.println("连接成功");
} catch (IOException e) {
try {
mmSocket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return ;
}
}
//在线程中管理连接;
}
public void cancel(){
try {
mmSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
方案二使用uuid;客服端进行连接,服务端接收连接
//<客服端》
public class ConnectThread extends Thread {
private final BluetoothDevice mmdevice;
private final BluetoothSocket mmSocket;
public final String s = "00001101-0000-1000-8000-00805F9B34FB";
private Boolean isConnect = false;
public ConnectThread(BluetoothDevice device){
BluetoothSocket tmp = null;
//赋值给设备
mmdevice = device;
try {
//根据UUID创建并返回一个BluetoothSocket
tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(s));
} catch(IOException e) {}
//赋值给BluetoothSocket
mmSocket = tmp;
}
public void run(){
try {
System.out.println("连接ing.....");
mmSocket.connect();
isConnect = true;
System.out.println("连接成功");
} catch (IOException e) {
try {
mmSocket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return ;
}
}
//在线程中管理连接;
}
public void cancel(){
try {
mmSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//服务端
private final BluetoothServerSocket mmserverSocket;
public AcceptThread(){
BluetoothServerSocket tmp = null;
try {
tmp = BluetoothAdapter.getDefaultAdapter().listenUsingRfcommWithServiceRecord("蓝牙连接", UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mmserverSocket = tmp;
}
public void run(){
BluetoothSocket Socket = null;
while(true){
try {
Socket = mmserverSocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
break;
}
if(Socket == null){
try {
//manageConnectedSocket(Socket);
mmserverSocket.close();
break;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void cancel(){
try {
mmserverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
朋友,可以添加戳这里获取](https://bbs.csdn.net/topics/618668825)**
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!