实验效果图:
实现需要的权限:由于安卓4.x以上的版本使用蓝牙,需要开启定位权限才能搜索到附近的蓝牙设备
<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />服务端
public class MainActivity extends AppCompatActivity implements View.OnClickListener { BluetoothSocket BTSocket;BluetoothAdapter BTAdapter;Button bt_start;TextView tv_msg;StringBuilder sb; @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);bt_start = (Button) findViewById(R.id.bt_start);tv_msg = (TextView) findViewById(R.id.tv_msg);bt_start.setOnClickListener(this);sb = new StringBuilder();//拿到本地蓝牙设备BTAdapter = BluetoothAdapter.getDefaultAdapter();} /*** UI文本输出** @param msg*/public void show(String msg) {sb.append(msg + " ");runOnUiThread(new Runnable() {@Overridepublic void run() {tv_msg.setText(sb.toString());}});} @Overridepublic void onClick(View v) {//开启服务器ServerThread startServerThread = new ServerThread();startServerThread.start();} /*** 开启服务器*/private class ServerThread extends Thread {public void run() {try {BluetoothServerSocket mserverSocket = BTAdapter.listenUsingRfcommWithServiceRecord("btspp", UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));show("服务端:等待连接"); BTSocket = mserverSocket.accept();show("服务端:连接成功"); readThread mreadThread = new readThread();mreadThread.start();show("服务端:启动接受数据");} catch (IOException e) {e.printStackTrace();}}} /*** 读取数据*/private class readThread extends Thread {public void run() {byte[] buffer = new byte[1024];int bytes;InputStream mmInStream = null;try {mmInStream = BTSocket.getInputStream();show("服务端:获得输入流");} catch (IOException e1) {e1.printStackTrace();}while (true) {try { if ((bytes = mmInStream.read(buffer)) > 0) { byte[] buf_data = new byte[bytes]; for (int i = 0; i < bytes; i++) { buf_data[i] = buffer[i]; } String s = new String(buf_data); show("服务端:读取数据了~~" + s); }} catch (IOException e) { try { mmInStream.close(); } catch (IOException e1) { e1.printStackTrace(); } break;}}}}}客户端
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private TextView tv_msg;private Button bt_search, bt_send;private BluetoothSocket BTSocket;private BluetoothAdapter BTAdapter;private BluetoothDevice device;private StringBuilder sb; @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main); bt_search = (Button) findViewById(R.id.bt_search);bt_send = (Button) findViewById(R.id.bt_send);tv_msg = (TextView) findViewById(R.id.tv_msg);bt_search.setOnClickListener(this);bt_send.setOnClickListener(this);sb = new StringBuilder(); show("客户端:检查BT");checkBT(this);show("客户端:注册接收者");registerBTReceiver();} /*** UI文本输出** @param msg*/public void show(String msg) {sb.append(msg + " ");runOnUiThread(new Runnable() {@Overridepublic void run() {tv_msg.setText(sb.toString());}});} @Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.bt_search:show("客户端:开始寻找设备");BTAdapter.startDiscovery();break;case R.id.bt_send:sendMessage();break;}} /*** 检查蓝牙*/public void checkBT(Context context) {BTAdapter = BluetoothAdapter.getDefaultAdapter();if (BTAdapter != null) {if (!BTAdapter.isEnabled()) {Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);// 设置蓝牙可见性,最多300秒intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);context.startActivity(intent);}} else {System.out.println("本地设备驱动异常!");}} /*** 开启客户端*/private class clientThread extends Thread {public void run() {try {//创建一个Socket连接:只需要服务器在注册时的UUID号BTSocket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));//连接show("客户端:开始连接...");BTSocket.connect();show("客户端:连接成功");//启动接受数据show("客户端:启动接受数据");readThread mreadThread = new readThread();mreadThread.start();} catch (IOException e) {show("客户端:连接服务端异常!断开连接重新试一试");e.printStackTrace();}}} /*** 读取数据*/private class readThread extends Thread {public void run() {byte[] buffer = new byte[1024];int bytes;InputStream is = null;try {is = BTSocket.getInputStream();show("客户端:获得输入流");} catch (IOException e1) {e1.printStackTrace();}while (true) {try { if ((bytes = is.read(buffer)) > 0) { byte[] buf_data = new byte[bytes]; for (int i = 0; i < bytes; i++) { buf_data[i] = buffer[i]; } String s = new String(buf_data); show("客户端:读取数据了" + s); }} catch (IOException e) { try { is.close(); } catch (IOException e1) { e1.printStackTrace(); } break;}}}} /*** 发送数据*/public void sendMessage() {if (BTSocket == null) {Toast.makeText(this, "没有连接", Toast.LENGTH_SHORT).show();return;}try {OutputStream os = BTSocket.getOutputStream();os.write("我爱你dahsid132456@#%¥*".getBytes());os.flush();show("客户端:发送信息成功");} catch (IOException e) {e.printStackTrace();}} /*** 注册广播*/public void registerBTReceiver() {// 设置广播信息过滤IntentFilter intentFilter = new IntentFilter();intentFilter.addAction(BluetoothDevice.ACTION_FOUND);intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);// 注册广播接收器,接收并处理搜索结果registerReceiver(BTReceive, intentFilter);} /*** 注销广播*/public void unregisterBTReceiver() {unregisterReceiver(BTReceive);} @Overrideprotected void onDestroy() {super.onDestroy();unregisterBTReceiver();} /*** 广播接收者*/private BroadcastReceiver BTReceive = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();if (BluetoothDevice.ACTION_FOUND.equals(action)) {device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);show("客户端:找到的BT名:" + device.getName());// 如果查找到的设备符合要连接的设备,处理if (device.getName().equalsIgnoreCase("xu")) { show("客户端:配对xu蓝牙:"); // 搜索蓝牙设备的过程占用资源比较多,一旦找到需要连接的设备后需要及时关闭搜索 BTAdapter.cancelDiscovery(); // 获取蓝牙设备的连接状态 int connectState = device.getBondState(); switch (connectState) { // 未配对 case BluetoothDevice.BOND_NONE: show("客户端:开始配对:"); try { Method createBondMethod = BluetoothDevice.class.getMethod("createBond"); createBondMethod.invoke(device); } catch (Exception e) { e.printStackTrace(); } break; // 已配对 case BluetoothDevice.BOND_BONDED: try { show("客户端:开始连接:"); clientThread clientConnectThread = new clientThread(); clientConnectThread.start(); } catch (Exception e) { e.printStackTrace(); } break; }}} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {// 获取蓝牙设备的连接状态int connectState = device.getBondState();// 已配对if (connectState == BluetoothDevice.BOND_BONDED) { try { show("客户端:开始连接:"); clientThread clientConnectThread = new clientThread(); clientConnectThread.start(); } catch (Exception e) { e.printStackTrace(); }}}show(action);}}; }蓝牙广播内容: