`
wenzongliang
  • 浏览: 449814 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

蓝牙最简单的例子,最难得的简单

阅读更多
 /**
服务器端和客户端工程中都必须有这两个权限申请
<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();

好了,这是最简单的。防止出现异常等等。。。情况自己扩展

我的话费充值店-各种面额

电信100元仅售98.60 
联通100仅售99.00
移动100仅售99.30

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics