一、項(xiàng)目實(shí)現(xiàn)功能
1.兩臺(tái)設(shè)備可以通過(guò)藍(lán)牙進(jìn)行通信
2.模擬Client 和Server端實(shí)現(xiàn)簡(jiǎn)單的通信。
二、項(xiàng)目核心代碼
1.簡(jiǎn)要實(shí)現(xiàn)設(shè)備藍(lán)牙通信
如果想讓?xiě)?yīng)用啟動(dòng)設(shè)備發(fā)現(xiàn)或操縱藍(lán)牙設(shè)置,則除了 BLUETOOTH 權(quán)限以外,還必須聲明 BLUETOOTH_ADMIN 權(quán)限。大多數(shù)應(yīng)用只是需利用此權(quán)限發(fā)現(xiàn)本地藍(lán)牙設(shè)備。除非應(yīng)用是根據(jù)用戶(hù)請(qǐng)求修改藍(lán)牙設(shè)置的“超級(jí)管理員”,否則不應(yīng)使用此權(quán)限所授予的其他功能。在Manifest.xml中加入以下代碼
在這里插入代碼片<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!-- If your app targets Android 9 or lower, you can declare
ACCESS_COARSE_LOCATION instead. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
...
</manifest>``
布局文件:
activity.xml主要布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/title_left_text"
style="?android:attr/windowTitleStyle"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_weight="1"
android:gravity="left"
android:ellipsize="end"
android:singleLine="true" />
<TextView
android:id="@+id/title_right_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_weight="1"
android:ellipsize="end"
android:gravity="right"
android:singleLine="true"
android:textColor="#fff" />
</LinearLayout>
<ListView android:id="@+id/in"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll"
android:layout_weight="1" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText android:id="@+id/edit_text_out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="bottom" />
<Button android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/send"/>
</LinearLayout>
</LinearLayout>
device_list.xm文件
option 布局
java文件:
BluetoothChat.java文件 檢測(cè)藍(lán)牙是否授權(quán),啟動(dòng)的activity文件
package com.example.bluetooth;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;
public class BluetoothChat extends AppCompatActivity{
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
private static final int REQUEST_CONNECT_DEVICE = 1; //請(qǐng)求連接設(shè)備
private static final int REQUEST_ENABLE_BT = 2;
private TextView title;
private ListView conversationView;
private EditText outEditText;
private Button send;
private String connectedDeviceName = null;
private ArrayAdapter<String> adapter1; // conversation array adapter
private StringBuffer outStringBuffer;
private BluetoothAdapter adapter2 = null;
private ChatService chatService = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide(); //隱藏標(biāo)題欄
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
}
Toolbar toolbar = findViewById(R.id.toolbar);
//創(chuàng)建選項(xiàng)菜單
toolbar.inflateMenu(R.menu.option_menu);
//選項(xiàng)菜單監(jiān)聽(tīng)
toolbar.setOnMenuItemClickListener(new MyMenuItemClickListener());
title = findViewById(R.id.title_left_text);
title.setText(R.string.app_name);
title = findViewById(R.id.title_right_text);
// 得到本地藍(lán)牙適配器
adapter2 = BluetoothAdapter.getDefaultAdapter();
if (adapter2 == null) {
Toast.makeText(this, "藍(lán)牙不可用", Toast.LENGTH_LONG).show();
finish();
return;
}
if (!adapter2.isEnabled()) { //若當(dāng)前設(shè)備藍(lán)牙功能未開(kāi)啟
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT); //
} else {
if (chatService == null) {
setupChat(); //創(chuàng)建會(huì)話
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults.length>0){
if(grantResults[0]!=PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "未授權(quán),藍(lán)牙搜索功能將不可用!", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public synchronized void onResume() { //synchronized:同步方法實(shí)現(xiàn)排隊(duì)調(diào)用
super.onResume();
if (chatService != null) {
if (chatService.getState() == ChatService.STATE_NONE) {
chatService.start();
}
}
}
private void setupChat() {
adapter1 = new ArrayAdapter<String>(this, R.layout.activity_main);
conversationView = findViewById(R.id.in);
conversationView.setAdapter(adapter1);
outEditText = findViewById(R.id.edit_text_out);
outEditText.setOnEditorActionListener(mWriteListener);
send = findViewById(R.id.button_send);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView view = findViewById(R.id.edit_text_out);
String message = view.getText().toString();
sendMessage(message);
}
});
//創(chuàng)建服務(wù)對(duì)象
chatService = new ChatService(this, mHandler);
outStringBuffer = new StringBuffer("");
}
@Override
public void onDestroy() {
super.onDestroy();
if (chatService != null)
chatService.stop();
}
// 直接使用enable()函數(shù)不安全,需要將內(nèi)容存放在intent中
private void ensureDiscoverable() { //修改本機(jī)藍(lán)牙設(shè)備的可見(jiàn)性
//打開(kāi)手機(jī)藍(lán)牙后,能被其它藍(lán)牙設(shè)備掃描到的時(shí)間不是永久的
if (adapter2.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//設(shè)置在300秒內(nèi)可見(jiàn)(能被掃描)
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
Toast.makeText(this, "已經(jīng)設(shè)置本機(jī)藍(lán)牙設(shè)備的可見(jiàn)性,對(duì)方可搜索了。", Toast.LENGTH_SHORT).show();
}
}
private void sendMessage(String message) {
if (chatService.getState() != ChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
byte[] send = message.getBytes();
chatService.write(send);
outStringBuffer.setLength(0);
outEditText.setText(outStringBuffer);
}
}
private TextView.OnEditorActionListener mWriteListener = new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
//軟鍵盤(pán)里的回車(chē)也能發(fā)送消息
String message = view.getText().toString();
sendMessage(message);
}
return true;
}
};
//使用Handler對(duì)象在UI主線程與子線程之間傳遞消息
private final Handler mHandler = new Handler() { //消息處理
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ChatService.STATE_CONNECTED:
title.setText(R.string.title_connected_to);
title.append(connectedDeviceName);
adapter1.clear();
break;
case ChatService.STATE_CONNECTING:
title.setText(R.string.title_connecting);
break;
case ChatService.STATE_LISTEN:
case ChatService.STATE_NONE:
title.setText(R.string.title_not_connected);
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
adapter1.add("我: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
adapter1.add(connectedDeviceName + ": "
+ readMessage);
break;
case MESSAGE_DEVICE_NAME:
connectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(),"鏈接到 " + connectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(),
msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
break;
}
}
};
//返回進(jìn)入好友列表操作后的數(shù)回調(diào)方法
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getExtras().getString(DeviceList.EXTRA_DEVICE_ADDRESS);
BluetoothDevice device = adapter2.getRemoteDevice(address);
chatService.connect(device);
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(this, "未選擇任何好友!", Toast.LENGTH_SHORT).show();
}
break;
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
setupChat();
} else {
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
}
}
//內(nèi)部類(lèi),選項(xiàng)菜單的單擊事件處理
private class MyMenuItemClickListener implements Toolbar.OnMenuItemClickListener {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.scan:
//啟動(dòng)DeviceList這個(gè)Activity
Intent serverIntent = new Intent(BluetoothChat.this, DeviceList.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
return true;
case R.id.discoverable:
ensureDiscoverable();
return true;
case R.id.back:
finish();
System.exit(0);
return true;
}
return false;
}
}
}
ChatService.java文件,藍(lán)牙服務(wù)的會(huì)話程序 定義了3個(gè)內(nèi)部類(lèi),AcceptThread(接受新連接)、ConnectThread(發(fā)出連接)和ConnectedThread (已連接)
package com.example.bluetooth;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
public class ChatService {
//本應(yīng)用的主Activity組件名稱(chēng)
private static final String NAME = "BluetoothChat";
// UUID:通用唯一識(shí)別碼,是一個(gè)128位長(zhǎng)的數(shù)字,一般用十六進(jìn)制表示
//算法的核心思想是結(jié)合機(jī)器的網(wǎng)卡、當(dāng)?shù)貢r(shí)間、一個(gè)隨機(jī)數(shù)來(lái)生成
//在創(chuàng)建藍(lán)牙連接
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private final BluetoothAdapter adapter;
private final Handler mHandler;
private AcceptThread acceptThread;
private ConnectThread connectThread;
private ConnectedThread connectedThread;
private int state;
public static final int STATE_NONE = 0;
public static final int STATE_LISTEN = 1;
public static final int STATE_CONNECTING = 2;
public static final int STATE_CONNECTED = 3;
//構(gòu)造方法,接收UI主線程傳遞的對(duì)象
public ChatService(Context context, Handler handler) {
//構(gòu)造方法完成藍(lán)牙對(duì)象的創(chuàng)建
adapter = BluetoothAdapter.getDefaultAdapter();
state = STATE_NONE;
mHandler = handler;
}
private synchronized void setState(int state) {
state = state;
mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
}
public synchronized int getState() {
return state;
}
public synchronized void start() {
if (connectThread != null) {
connectThread.cancel();
connectThread = null;
}
if (connectedThread != null) {
connectedThread.cancel();
connectedThread = null;
}
if (acceptThread == null) {
acceptThread = new AcceptThread();
acceptThread.start();
}
setState(STATE_LISTEN);
}
//取消 CONNECTING 和 CONNECTED 狀態(tài)下的相關(guān)線程,然后運(yùn)行新的 connectThread 線程
public synchronized void connect(BluetoothDevice device) {
if (state == STATE_CONNECTING) {
if (connectThread != null) {
connectThread.cancel();
connectThread = null;
}
}
if (connectedThread != null) {
connectedThread.cancel();
connectedThread = null;
}
connectThread = new ConnectThread(device);
connectThread.start();
setState(STATE_CONNECTING);
}
/*
開(kāi)啟一個(gè) ConnectedThread 來(lái)管理對(duì)應(yīng)的當(dāng)前連接。之前先取消任意現(xiàn)存的 connectThread 、
connectedThread 、 acceptThread 線程,然后開(kāi)啟新 connectedThread ,傳入當(dāng)前剛剛接受的
socket 連接。最后通過(guò) Handler來(lái)通知UI連接
*/
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
if (connectThread != null) {
connectThread.cancel();
connectThread = null;
}
if (connectedThread != null) {
connectedThread.cancel();
connectedThread = null;
}
if (acceptThread != null) {
acceptThread.cancel();
acceptThread = null;
}
connectedThread = new ConnectedThread(socket);
connectedThread.start();
Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
setState(STATE_CONNECTED);
}
// 停止所有相關(guān)線程,設(shè)當(dāng)前狀態(tài)為 NONE
public synchronized void stop() {
if (connectThread != null) {
connectThread.cancel();
connectThread = null;
}
if (connectedThread != null) {
connectedThread.cancel();
connectedThread = null;
}
if (acceptThread != null) {
acceptThread.cancel();
acceptThread = null;
}
setState(STATE_NONE);
}
// 在 STATE_CONNECTED 狀態(tài)下,調(diào)用 connectedThread 里的 write 方法,寫(xiě)入 byte
public void write(byte[] out) {
ConnectedThread r;
synchronized (this) {
if (state != STATE_CONNECTED)
return;
r = connectedThread;
}
r.write(out);
}
// 連接失敗的時(shí)候處理,通知 ui ,并設(shè)為 STATE_LISTEN 狀態(tài)
private void connectionFailed() {
setState(STATE_LISTEN);
Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(BluetoothChat.TOAST, "鏈接不到設(shè)備");
msg.setData(bundle);
mHandler.sendMessage(msg);
}
// 當(dāng)連接失去的時(shí)候,設(shè)為 STATE_LISTEN 狀態(tài)并通知 ui
private void connectionLost() {
setState(STATE_LISTEN);
Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(BluetoothChat.TOAST, "設(shè)備鏈接中斷");
msg.setData(bundle);
mHandler.sendMessage(msg);
}
// 創(chuàng)建監(jiān)聽(tīng)線程,準(zhǔn)備接受新連接。使用阻塞方式,調(diào)用 BluetoothServerSocket.accept()
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
//使用射頻端口(RF comm)監(jiān)聽(tīng)
tmp = adapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
}
mmServerSocket = tmp;
}
@Override
public void run() {
setName("AcceptThread");
BluetoothSocket socket = null;
while (state != STATE_CONNECTED) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
if (socket != null) {
synchronized (ChatService.this) {
switch (state) {
case STATE_LISTEN:
case STATE_CONNECTING:
connected(socket, socket.getRemoteDevice());
break;
case STATE_NONE:
case STATE_CONNECTED:
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
}
}
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
連接線程,專(zhuān)門(mén)用來(lái)對(duì)外發(fā)出連接對(duì)方藍(lán)牙的請(qǐng)求和處理流程。
構(gòu)造函數(shù)里通過(guò) BluetoothDevice.createRfcommSocketToServiceRecord() ,
從待連接的 device 產(chǎn)生 BluetoothSocket. 然后在 run 方法中 connect ,
成功后調(diào)用 BluetoothChatSevice 的 connected() 方法。定義 cancel() 在關(guān)閉線程時(shí)能夠關(guān)閉相關(guān)socket 。
*/
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
mmSocket = tmp;
}
@Override
public void run() {
setName("ConnectThread");
adapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException e) {
connectionFailed();
try {
mmSocket.close();
} catch (IOException e2) {
e.printStackTrace();
}
ChatService.this.start();
return;
}
synchronized (ChatService.this) {
connectThread = null;
}
connected(mmSocket, mmDevice);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
雙方藍(lán)牙連接后一直運(yùn)行的線程;構(gòu)造函數(shù)中設(shè)置輸入輸出流。
run()方法中使用阻塞模式的 InputStream.read()循環(huán)讀取輸入流,然后發(fā)送到 UI 線程中更新聊天消息。
本線程也提供了 write() 將聊天消息寫(xiě)入輸出流傳輸至對(duì)方,傳輸成功后回寫(xiě)入 UI 線程。最后使用cancel()關(guān)閉連接的 socket
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
@Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = mmInStream.read(buffer);
mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
connectionLost();
break;
}
}
}
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
} catch (IOException e) {
e.printStackTrace();
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
DeviceList.java文件
本程序供菜單項(xiàng)主界面的選項(xiàng)菜單“我的友好”調(diào)用,用于:
(1)顯示已配對(duì)的好友列表;
(2)搜索可配對(duì)的好友進(jìn)行配對(duì)
(3)新選擇并配對(duì)的藍(lán)牙設(shè)備將刷新好友列表
注意:發(fā)現(xiàn)新的藍(lán)牙設(shè)備并請(qǐng)求配對(duì)時(shí),需要對(duì)應(yīng)接受
關(guān)鍵技術(shù):動(dòng)態(tài)注冊(cè)一個(gè)廣播接收者,處理藍(lán)牙設(shè)備掃描的結(jié)果
package com.example.bluetooth;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Set;
public class DeviceList extends AppCompatActivity {
private BluetoothAdapter adapter;
private ArrayAdapter<String> adapter1; // 配對(duì)的設(shè)備
private ArrayAdapter<String> adapter2; // 新設(shè)備
public static String EXTRA_DEVICE_ADDRESS = "device_address"; //Mac地址
//定義廣播接收者,用于處理掃描藍(lán)牙設(shè)備后的結(jié)果
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
adapter2.add(device.getName() + "\n" + device.getAddress());
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
if (adapter2.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
adapter2.add(noDevices);
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_list);
//在被調(diào)用活動(dòng)里,設(shè)置返回結(jié)果碼
setResult(Activity.RESULT_CANCELED);
init(); //活動(dòng)界面
}
private void init() {
Button scanButton = findViewById(R.id.button_scan);
scanButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(DeviceList.this, R.string.scanning, Toast.LENGTH_LONG).show();
doDiscovery(); //搜索藍(lán)牙設(shè)備
}
});
adapter1 = new ArrayAdapter<String>(this, R.layout.activity_main);
adapter2 = new ArrayAdapter<String>(this, R.layout.activity_main);
//已配對(duì)藍(lán)牙設(shè)備列表
ListView pairedListView =findViewById(R.id.paired_devices);
pairedListView.setAdapter(adapter1);
pairedListView.setOnItemClickListener(mPaireDeviceClickListener);
//未配對(duì)藍(lán)牙設(shè)備列表
ListView newDevicesListView = findViewById(R.id.new_devices);
newDevicesListView.setAdapter(adapter2);
newDevicesListView.setOnItemClickListener(mNewDeviceClickListener);
//動(dòng)態(tài)注冊(cè)廣播接收者
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver, filter);
adapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
adapter1.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired).toString();
adapter1.add(noDevices);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (adapter != null) {
adapter.cancelDiscovery();
}
this.unregisterReceiver(receiver);
}
private void doDiscovery() {
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
if (adapter.isDiscovering()) {
adapter.cancelDiscovery();
}
adapter.startDiscovery(); //開(kāi)始搜索藍(lán)牙設(shè)備并產(chǎn)生廣播
//startDiscovery是一個(gè)異步方法
//找到一個(gè)設(shè)備時(shí)就發(fā)送一個(gè)BluetoothDevice.ACTION_FOUND的廣播
}
private AdapterView.OnItemClickListener mPaireDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
adapter.cancelDiscovery();
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address); //Mac地址
setResult(Activity.RESULT_OK, intent);
finish();
}
};
private AdapterView.OnItemClickListener mNewDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
adapter.cancelDiscovery();
Toast.makeText(DeviceList.this, "請(qǐng)?jiān)谒{(lán)牙設(shè)置界面手動(dòng)連接設(shè)備",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
startActivityForResult(intent,1);
}
};
//回調(diào)方法:進(jìn)入藍(lán)牙配對(duì)設(shè)置界面返回后執(zhí)行
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
init(); //刷新好友列表
}
}
2.模擬Client 和Server端實(shí)現(xiàn)簡(jiǎn)單的通信。
Client端 布局文件
button用以開(kāi)關(guān)藍(lán)牙以及搜索設(shè)備的布局按鈕
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/lis1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ToggleButton
android:id="@+id/bu5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="本機(jī)狀態(tài):" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="搜索設(shè)備" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="設(shè)置" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打開(kāi)" />
</ListView>
</LinearLayout>
mainactivity.java
package com.example.gwlblu;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
//藍(lán)牙通信需要相同的UUID和對(duì)方的藍(lán)牙地址,UUID規(guī)定是下面的格式,只要格式對(duì),兩邊的UUID相同,數(shù)字可以改變,不影響通信,但一般都是用下面這種
static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
Button btnSearch, btnDis;//定義布局中的按鈕
ToggleButton tbtnSwitch;//顯示藍(lán)牙開(kāi)關(guān)狀態(tài)的雙狀態(tài)按鈕
ListView lvBTDevices; //搜索到的藍(lán)牙列表
ArrayAdapter<String> adtDevices; //將本機(jī)的藍(lán)牙地址顯示
List<String> lstDevices = new ArrayList<String>();//列表中藍(lán)牙的地址
BluetoothAdapter btAdapt; //定義移動(dòng)設(shè)備的本地的藍(lán)牙適配器
public static BluetoothSocket btSocket; //Socket用來(lái)接受客戶(hù)端的要求
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //加載 布局
// Button 設(shè)置 通過(guò)findViewById的方法來(lái)定義
//獲得所有控件對(duì)象
btnSearch = (Button) this.findViewById(R.id.button2);
btnDis = (Button) this.findViewById(R.id.button3);
tbtnSwitch = (ToggleButton) this.findViewById(R.id.bu5);
//給所有的控件設(shè)置監(jiān)聽(tīng)器
btnDis.setOnClickListener(new ClickEvent());
btnSearch.setOnClickListener(new ClickEvent());
tbtnSwitch.setOnClickListener(new ClickEvent());
// ListView及其數(shù)據(jù)源 適配器
lvBTDevices = (ListView) this.findViewById(R.id.lis1);
adtDevices = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, lstDevices);
lvBTDevices.setAdapter(adtDevices);
lvBTDevices.setOnItemClickListener(new ItemClickEvent());//設(shè)置監(jiān)聽(tīng)器獲取數(shù)據(jù)
btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本機(jī)藍(lán)牙功能
if (btAdapt.getState() == BluetoothAdapter.STATE_OFF)// 讀取藍(lán)牙狀態(tài)并顯示于雙狀態(tài)按鈕
tbtnSwitch.setChecked(false);
else if (btAdapt.getState() == BluetoothAdapter.STATE_ON)
tbtnSwitch.setChecked(true);
// 注冊(cè)Receiver來(lái)獲取藍(lán)牙設(shè)備相關(guān)的結(jié)果,onReceive()里取得搜索所得的藍(lán)牙設(shè)備信息
IntentFilter intent = new IntentFilter();
intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver來(lái)取得搜索結(jié)果
intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(searchDevices, intent);
}
private BroadcastReceiver searchDevices = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle b = intent.getExtras();
Object[] lstName = b.keySet().toArray();
// 顯示所有收到的消息及其細(xì)節(jié)
for (int i = 0; i < lstName.length; i++) {
String keyName = lstName[i].toString();
Log.e(keyName, String.valueOf(b.get(keyName)));
}
//搜索設(shè)備時(shí),取得設(shè)備的MAC地址
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String str= device.getName() + "|" + device.getAddress();
if (lstDevices.indexOf(str) == -1)// 防止重復(fù)添加,
lstDevices.add(str); // 獲取設(shè)備名稱(chēng)和mac地址
adtDevices.notifyDataSetChanged();//通知Activity刷新數(shù)據(jù)
}
}
};
//本次活動(dòng)的銷(xiāo)毀函數(shù)
@Override
protected void onDestroy() {
try {
if (btSocket != null)
btSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
this.unregisterReceiver(searchDevices);
super.onDestroy();
android.os.Process.killProcess(android.os.Process.myPid());
}
//對(duì)監(jiān)聽(tīng)器的設(shè)置,獲取列表中設(shè)備名以及藍(lán)牙設(shè)備地址
class ItemClickEvent implements AdapterView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
btAdapt.cancelDiscovery();//連接時(shí)停止搜索周?chē){(lán)牙,否則容易連接失敗
//取出藍(lán)牙地址
String str = lstDevices.get(arg2);
String[] values = str.split("\\|");
String address=values[1];
Log.d("address",values[1]);
UUID uuid = UUID.fromString(SPP_UUID);
//利用BluetoothDevice衍生出Socket,
BluetoothDevice btDev = btAdapt.getRemoteDevice(address);
try {
btSocket = btDev
.createRfcommSocketToServiceRecord(uuid);
try {
// 連接建立之前的先配對(duì)
if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
Method creMethod = BluetoothDevice.class
.getMethod("createBond");
Log.e("TAG", "開(kāi)始配對(duì)");
creMethod.invoke(btDev);
}
} catch (Exception e) {
e.printStackTrace();
}
btSocket.connect();
Toast.makeText(MainActivity.this,"connect succeeded",Toast.LENGTH_SHORT).show();
//將數(shù)據(jù)寫(xiě)入輸出流
OutputStream os = btSocket.getOutputStream();
if (os != null) {
try {
os.write("test".getBytes("UTF-8"));
Toast.makeText(MainActivity.this, "send succeed", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,"connect fail",Toast.LENGTH_LONG).show();
}
}
}
//按鈕監(jiān)聽(tīng)器,打開(kāi)本機(jī)藍(lán)牙的設(shè)置
class ClickEvent implements View.OnClickListener {
@Override
public void onClick(View v) {
if (v == btnSearch)// 搜索藍(lán)牙設(shè)備,在BroadcastReceiver顯示結(jié)果
{
if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果藍(lán)牙還沒(méi)開(kāi)啟
Toast.makeText(MainActivity.this, "請(qǐng)先打開(kāi)藍(lán)牙", Toast.LENGTH_LONG).show();
return;
}
setTitle("本機(jī)藍(lán)牙地址:" + btAdapt.getAddress());
lstDevices.clear();
btAdapt.startDiscovery();
} else if (v == tbtnSwitch) {// 本機(jī)藍(lán)牙啟動(dòng)/關(guān)閉
if (tbtnSwitch.isChecked() == false)
btAdapt.enable();
else if (tbtnSwitch.isChecked() == true)
btAdapt.disable();
} else if (v == btnDis)// 本機(jī)可以被搜索
{
Intent discoverableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);//本機(jī)藍(lán)牙的內(nèi)部設(shè)置
}
}
}
}
Server端
package com.example.gwlblu;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import java.io.InputStream;
import java.util.UUID;
public class Server extends AppCompatActivity {
private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");//Server端和Client端的UUID要一致
private BluetoothAdapter bluetoothAdapter;
private final String NAME = "BlueTooth_Socket";//名字可以隨便寫(xiě)
private AcceptThread acceptThread;//后面的accept()會(huì)阻塞,所以要新開(kāi)線程
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
acceptThread=new AcceptThread();
acceptThread.start();//開(kāi)啟線程
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Toast.makeText(Server.this, String.valueOf(msg.obj), Toast.LENGTH_SHORT).show();
}
};
private class AcceptThread extends Thread {
private BluetoothServerSocket serverSocket;
private BluetoothSocket socket;
private InputStream is;
public AcceptThread() {
try {
//監(jiān)聽(tīng)有無(wú)連接
serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (Exception e) {
}
}
@Override
public void run() {
try {
socket = serverSocket.accept();//若有監(jiān)聽(tīng)到有連接,accept給BluetoothSocket
Log.d("tag", "connected");
is = socket.getInputStream();
while (true) {
byte[] buffer = new byte[128];
int count = is.read(buffer);
//子線程里不能直接Toast,利用handler
Message msg = new Message();
msg.obj = new String(buffer, 0, count, "UTF-8");
handler.sendMessage(msg);
}
} catch (Exception e) {
}
}
}
}
三、實(shí)驗(yàn)項(xiàng)目截圖
實(shí)驗(yàn)1(真機(jī)調(diào)試):
簡(jiǎn)單實(shí)現(xiàn)藍(lán)牙通信聊天
實(shí)驗(yàn)2
實(shí)現(xiàn)功能:Client端三個(gè)按鈕,分別是藍(lán)牙開(kāi)關(guān)、本機(jī)可被搜索和搜索設(shè)備,點(diǎn)擊搜索設(shè)備即可搜索周?chē)乃{(lán)牙,點(diǎn)擊搜索到的藍(lán)牙即可連接并自動(dòng)發(fā)送test。Server端在接收到消息之后便Toast出來(lái)。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-435839.html
四、源代碼
gitee源代碼1
gitee源代碼2文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-435839.html
到了這里,關(guān)于Android Studio 簡(jiǎn)要實(shí)現(xiàn)藍(lán)牙(Bluetooth)通信(附加作業(yè))的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!