蓝牙最简单的例子,最难得的简单
<uses-permission android:name="android.permission.BLUETOOTH" />
关于UUID。。。UUID客户端和服务端一定要一致。UUID不能和其他的一样。一定要自己去申请一个
请从http://www.uuidgenerator.com上获取你自己的UUID
这行代码之前一定要确保蓝牙是打开状态的
打开蓝牙的代码(可以用BluetoothAdapter的方法enable()。关闭为disable())或
? ?? ?? ?? ?Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
? ?? ?? ?? ?startActivityForResult(enableIntent, REQUEST_ENABLE_BT);//会打开一个对话框询问是否打开蓝牙
? ???或startActivity(enableIntent)
可被搜索的代码
? ?? ?? ?? ?Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
? ?? ?? ?? ?discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
? ?? ?? ?? ?startActivity(discoverableIntent);
? ???或startActivityForResult(discoverableIntent)
*/
1.服务器端:
UUID uuid = uuid.fromString(”27648B4D-D854-5674-FA60E4F535E44AF7″);
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
BluetoothServerSocket serverSocket = adapter.listenUsingRfcommWithServiceRecord(”MyBluetoothApp”, uuid);
BluetoothSocket socket = serverSocket.accept();
2.客户端
UUID uuid = uuid.fromString(“27648B4D-D854-5674-FA60E4F535E44AF7″);
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = adapter.getRemoteDevice(“00:11:22:33:44:55″);//服务器的蓝牙地址
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
adapter.connect();
3.双方连接上后,就开始读写了
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
好了,这是最简单的。防止出现异常等等。。。情况自己扩展