一.蓝牙介绍:
二.蓝牙的作用:
三 .蓝牙工作原理以及涉及到的类:
四.蓝牙客户端代码:
五.蓝牙服务端代码:
一.蓝牙介绍:
是一种无线技术标准,可实现固定设备、移动设备和楼宇个人域网之间的短距离数据交换,我们主要掌握这几项技能:
添加权限:
<!-- 用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
打开蓝牙并设置允许被搜索
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);
startActivityForResult(intent,100);
//关闭蓝牙
bluetoothAdapter.disable();
//关闭蓝牙
bluetoothAdapter.disable();
//刷新匹配的设备
bluetoothAdapter.getBondedDevices();
//搜索附近设备
bluetoothAdapter.startDiscovery();
//使用蓝牙传输数据:socket和ServerSocket传输数据
服务器代码
new Thread(new Runnable() {
@Override
public void run() {
try {
BluetoothServerSocket serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(bluetoothAdapter.getName(), uuid);
while (true){
BluetoothSocket socket = serverSocket.accept();
new MyThread(socket,handler).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
//服务线程代码
package com.example.day09_bluetooth;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import java.io.IOException;
import java.io.InputStream;
public class MyThread extends Thread {
BluetoothSocket socket;
Handler handler;
public MyThread(BluetoothSocket socket, Handler handler) {
this.socket = socket;
this.handler = handler;
}
@Override
public void run() {
super.run();
try {
StringBuilder sb = new StringBuilder();
InputStream is = socket.getInputStream();
byte[] bytes=new byte[1024];
int len=0;
while ((len = is.read(bytes)) != -1){
String s = new String(bytes, 0, len);
sb.append(s);
Message obtain = Message.obtain();
obtain.what = 101;
obtain.obj = sb.toString();
handler.sendMessage(obtain);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//客户端代码
BluetoothSocket socket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid);
socket.connect();
socket.getOutputStream().write("无法理解".getBytes());