蓝牙最简单的例子,最难得的简单
/** 服务器端和客户端工程中都必须有这两个权限申请 <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <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(); 好了,这是最简单的。防止出现异常等等。。。情况自己扩展 |
相关推荐
八角塘塘主 2020-07-04
DAV数据库 2020-05-11
IBMRational 2020-03-07
suixinsuoyu 2020-02-22
Hashxu 2020-02-05
姚强 2020-01-08
chysunny 2019-12-17
jocleyn 2019-11-10
LuoXinLoves 2019-10-29
冷月醉雪 2016-11-24
89421950 2016-02-18
vagrant00 2014-05-02
89550492 2011-06-06
chenchuang 2010-10-27