今天学习了android蓝牙方面的基础知识,包含了打开和关闭蓝牙的操作,以及两部手机之间通过蓝牙实现的数据传输。下面看代码:
首先,需要在清单文件里添加蓝牙操作的权限:
<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
打开蓝牙的两种方式:
第一种:Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent,1);
这种方式会提示用户是否打开蓝牙
第二种:bluetoothAdapter.enable();
这种方式系统直接打开蓝牙
关闭蓝牙的操作:bluetoothAdapter.disable();
搜索附近蓝牙的基本操作:
1.BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//得到默认的蓝牙适配器
2.if (bluetoothAdapter.isDiscovering()) {//如果正好在搜索,则先取消搜索
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
第二部在搜索的时候,会发出一个广播BluetoothDevice.ACTION_FOUND
3.创建并注册BroadcastReceiver并在onReceive方法中进行操作,关键代码如下:
@Override public void onReceive(Context arg0, Intent arg1) { // TODO Auto-generated method stub String action = arg1.getAction(); //获得已经搜索到的蓝牙设备 if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = arg1.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); //搜索到的设备不是已经绑定的设备 if (device.getBondState() != BluetoothDevice.BOND_BONDED) { //将搜索到的新蓝牙设备和名称显示到textview中 show.append(device.getName()+":"+device.getAddress()+"\n"); } }else if (bluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {//说明搜索已经完成 setProgressBarIndeterminateVisibility(false); setTitle("搜索蓝牙设备"); } }
2.两个蓝牙设备之间的通信
在清单文件里添加蓝牙操作的权限:
<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
A.在两个手机上蓝牙之间传输数据是通过BluetoothSocket和BluetoothServerSocket来实现的
B.创建BluetoothSocket和BluetoothServerSocket的方式如下:
clientSocket = device
.createRfcommSocketToServiceRecord(MY_UUID);
serverSocket = bluetoothAdapter
.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
这里需要注意的是:
UUID MY_UUID = UUID
.fromString("5dd231bf-d217-4e85-a26c-5e5cfda9aa0c");
5dd231bf-d217-4e85-a26c-5e5cfda9aa0c是有系统提供的UUID.randomUUID().toString();生成的可以用于蓝牙设备之间的传输身份证,这个是唯一的
NAME是一个字符串,是我们随便给的
B.创建接受数据的线程类:
private class AcceptThread extends Thread{ private BluetoothServerSocket serverSocket; private BluetoothSocket socket; private InputStream is; private OutputStream os; public AcceptThread() { //创建BluetoothServerSocket对象 try { serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("name",UUID.fromString("5dd231bf-d217-4e85-a26c-5e5cfda9aa0c")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void run() { // TODO Auto-generated method stub //等待接受蓝牙客户端的请求 try { socket = serverSocket.accept(); is = socket.getInputStream(); os = socket.getOutputStream(); while(true){ byte[] buffer = new byte[128]; int count = is.read(buffer); Message message = new Message(); message.obj = new String(buffer,0, count, "utf-8"); handler.sendMessage(message); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
得到已经绑定的蓝牙设备并用list显示出来
luetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//得到默认的蓝牙适配器 C.Set<BluetoothDevice>paireDevices = bluetoothAdapter.getBondedDevices();//得到已经绑定的蓝牙设备 if (paireDevices.size() > 0) {//若存在 String []data = new String[paireDevices.size()]; for (BluetoothDevice bluetoothDevice : paireDevices) { data[count++] = bluetoothDevice.getName()+":"+bluetoothDevice.getAddress();//得到绑定蓝牙设备的名称和地址 } adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_expandable_list_item_1,data); list.setAdapter(adapter);
为list的每一个列表项绑定监听事件:
list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub String s = adapter.getItem(position); //获得要连接的蓝牙设备的地址 String address = s.substring(s.indexOf(":")+1).trim(); if (null == device) { //获得蓝牙设备,相当于网路客户端制定的socketip地址 device = bluetoothAdapter.getRemoteDevice(address); } if (null == clientSocket) { try { clientSocket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("5dd231bf-d217-4e85-a26c-5e5cfda9aa0c")); //开始连接蓝牙设备 clientSocket.connect(); os = clientSocket.getOutputStream(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (null != os) { //向服务器端发送一个字符串 try { os.write("这是另一台手机发送过来的数据".getBytes("utf-8")); Toast.makeText(MainActivity.this,"发送成功",1000); } catch (Exception e) { // TODO Auto-generated catch block Toast.makeText(MainActivity.this,"发送失败",1000); e.printStackTrace(); } } } } } );
分别将该应用部署到两部手机,实现蓝牙通信.注意目前这种方式只支持简单的数据传输,如果需要出书二进制文件,比如音频,还是不可以的。
原文地址:http://blog.csdn.net/mockingbirds/article/details/44840071