采用普通藍(lán)牙技術(shù),也就是BluetoothSokcet相關(guān)API進(jìn)行數(shù)據(jù)傳輸。
思路:首先準(zhǔn)備,客戶端和服務(wù)端。兩臺手機(jī)即可。
藍(lán)牙需要服務(wù)端啟動accept監(jiān)聽是否有客戶端進(jìn)行相關(guān)鏈接,在這個模式下一個服務(wù)端僅僅允許鏈接一個客戶端,一對一。其他客戶端進(jìn)行鏈接都會報timeout錯誤。
上代碼
第一步,動態(tài)申請藍(lán)牙權(quán)限
//1.清單文件增加以下權(quán)限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
//2.代碼申請權(quán)限
private void applyPermission() {
if (Build.VERSION.SDK_INT >= 23) {
int checkPermission = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION);
if (checkPermission != PackageManager.PERMISSION_GRANTED) {
Logger.print("request permission");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
isPermission = true;
Toaster.show("已授權(quán)");
} else {
isPermission = false;
Toaster.show("拒絕授權(quán)");
}
}
第二步,獲取藍(lán)牙適配器bluetoothAdapter(客戶端服務(wù)端都需要,但是服務(wù)端不需要掃描)
//獲取藍(lán)牙適配器
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
public void searchBluetooth(View view) {
applyPermission();//申請權(quán)限
if (bluetoothAdapter == null) {
Toaster.show("不支持藍(lán)牙");
return;
}
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
}
if (bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//設(shè)置300內(nèi)可見
startActivity(discoverableIntent);
}
doDiscovery();//掃描藍(lán)牙 客戶端需要
}
//開始掃描
public void doDiscovery() {
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
} else {
bluetoothAdapter.startDiscovery();
}
}
第三步,客戶端注冊廣播接收藍(lán)牙
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);//注冊廣播信號
registerReceiver(bluetoothReceiver, intentFilter);
private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null && BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Logger.print("名稱 : " + device.getName() + "地址 : " + device.getAddress());
if (device != null && device.getName() != null && device.getAddress() != null) {
blueData.add(device);
adapter.notifyDataSetChanged();//適配器刷新list獲取已鏈接的藍(lán)牙列表
}
}
}
};
第四步,啟動一個子線程進(jìn)行鏈接服務(wù)器的socket
ClientThread clientThread = new ClientThread(device);
new Thread(clientThread).start();
class ClientThread extends Thread {
BluetoothDevice device;
public BluetoothSocket socket;
public ClientThread(BluetoothDevice device) {
this.device = device;
}
@Override
public void run() {
super.run();
try {
socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
//這里的UUID必須和服務(wù)端一致,否則肯定會鏈接失敗
bluetoothAdapter.cancelDiscovery();
socket.connect();
Logger.print("客戶端已鏈接服務(wù)端.");
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
//鏈接成功后,再次啟動一個線程不斷讀取服務(wù)器發(fā)過來的消息
new ClientInputStream(inputStreamReader,socket).start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ClientInputStream extends Thread {
InputStreamReader br;
BluetoothSocket socket;
public boolean isRunning = true;
public ClientInputStream(InputStreamReader br, BluetoothSocket socket) {
this.br = br;
this.socket = socket;
}
@Override
public void run() {
super.run();
while (isRunning) {
try {
char[] data = new char[1024];
int read = br.read(data);
Logger.print("服務(wù)端的消息:"+new String(data,0,read));
} catch (IOException e) {
e.printStackTrace();
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
isRunning = false;
}
}
Logger.print("服務(wù)器已斷開");
}
}
第五步,服務(wù)端 服務(wù)端其他代碼和客戶端差不多。線程不一樣還有發(fā)送消息測試
class ServerThread extends Thread {
BluetoothAdapter adapter;
public BluetoothServerSocket serverSocket;
public BluetoothSocket socket;
public OutputStreamWriter osw;
public ServerThread(BluetoothAdapter adapter) {
this.adapter = adapter;
}
@Override
public void run() {
super.run();
try {
Logger.print("服務(wù)端啟動");
serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(bluetoothAdapter.getDefaultAdapter().getName()
, UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));//生成服務(wù)端socket
socket = serverSocket.accept();//等待客戶端鏈接,這里會進(jìn)行阻塞。
osw = new OutputStreamWriter(socket.getOutputStream(),"UTF-8");
Logger.print("服務(wù)端鏈接成功");
} catch (Exception e) {
e.printStackTrace();
}
}
}
第七步,發(fā)送消息測試,注意要用子線程進(jìn)行發(fā)送消息
public void sendMsg(View view) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
OutputStreamWriter os = ct.osw;
if(os ==null){
Logger.print("客戶端未鏈接");
return;
}
String msg = "服務(wù)端測試信息";
os.write(msg);
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
};
new Thread(runnable).start();
}