藍牙通信的簡要設計與開發
- 藍牙通信步驟
- 具體步驟
- 程序圖及其文字描述
- 藍牙通信原理
- 藍牙客戶端socket作業步驟
- 藍牙服務端socket作業步驟
- Android Studio實作
- 配置權限
- 狀態描述文本及配色
- 藍牙服務
- 設備顯示
- 切換主MainActivity為BluetoothChat
- actvity_main.xml
- option_menu.xml
- device_list.xml
- device_name.xml
- message.xml
- 效果截圖
- 參考博客
- Git鏈接
藍牙通信步驟
具體步驟
1,首先開啟藍牙
2、搜索可用設備
3、創建藍牙socket,獲取輸入輸出流
4、讀取和寫入資料
5、斷開連接關閉藍牙
程序圖及其文字描述

1.執行oncreate方法打開藍牙,不需要經過用戶的同意;
2.通過注冊廣播接收器獲取搜索到的藍牙設備,在串列上顯示搜索到的設備;
3.點擊所顯示的設備調連接藍牙的代碼請求連接!
4.連接具體解釋,連接時和socket聊天的方式近似;
5在此做出假設;假設藍牙設備A向藍牙設備B發送一串文字;首先呼叫相關的藍牙連接代碼建立連接;
6獲取輸出流通過socket發送資料到另外—個藍牙設備;需要設定發送時的ID∶定義類似埠型別的;
7.接收端設備B需要獲取輸入流讀取藍牙設備A發送過來的訊息;然后在界面上顯示;
藍牙通信原理
首先要知道幾個類
BluetoothAdapter:代表本地藍牙配接器(藍牙無線電),BluetoothAdapter是所有藍牙互動的入口,使用這個你可以發現其他藍牙設備,查詢已配對的設備串列,使用一個已知的MAC地址來實體化一個BluetoothDevice,以及創建一個BluetoothServerSocket來為監聽與其他設備的通信,
BluetoothGatt:BluetoothGatt作為中央來使用和處理資料,使用時有一個回呼方法BluetoothGattCallback回傳中央的狀態和周邊提供的資料
BluetoothDevice:代表一個遠程藍牙設備,使用這個來請求一個與遠程設備的BluetoothSocket連接,或者查詢關于設備名稱、地址、類和連接狀態等設備資訊,
BluetoothCattService:BluetoothCattService作為周邊來提供資料
BluetoothCattCharacteristic:BluetoothCattCharacteristic是藍牙設備的特征
BluetoothGattServerCallback:BluetoothGattServerCallback回傳周邊的狀態
藍牙客戶端socket作業步驟
1、創建客戶端藍牙Sokcet
2、創建連接
3、讀寫資料
4、關閉
藍牙服務端socket作業步驟
1、創建服務端藍牙Socket
2、系結埠號(藍牙忽略)
3、創建監聽listen(藍牙忽略, 藍牙沒有此監聽,而是通過whlie(true)死回圈來一直監聽的)
4、通過accept(),如果有客戶端連接,會創建一個新的Socket,體現出并發性,可以同時與多個socket通訊)
5、讀寫資料
6、關閉
Android Studio實作
配置權限
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
狀態描述文本及配色
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MyBluetooth</string>
<string name="send">發送</string>
<string name="not_connected">你沒有鏈接一個設備</string>
<string name="bt_not_enabled_leaving">藍牙不可用,離開聊天室</string>
<string name="title_connecting">鏈接中...</string>
<string name="title_connected_to">連接到:</string>
<string name="title_not_connected">無鏈接</string>
<string name="scanning">藍牙設備搜索中...</string>
<string name="select_device">選擇一個好友鏈接</string>
<string name="none_paired">沒有配對好友</string>
<string name="none_found">附近沒有發現好友</string>
<string name="title_paired_devices">已配對好友</string>
<string name="title_other_devices">其它可連接好友</string>
<string name="button_scan">搜索好友</string>
<string name="connect">我的好友</string>
<string name="discoverable">設定在線</string>
<string name="back">退出</string>
<string name="startVideo">開始聊天</string>
<string name="stopVideo">結束聊天</string>
</resources>
藍牙服務
public class ChatService {
//本應用的主Activity組件名稱
private static final String NAME = "BluetoothChat";
// UUID:通用唯一識別碼,是一個128位長的數字,一般用十六進制表示
//演算法的核心思想是結合機器的網卡、當地時間、一個亂數來生成
//在創建藍牙連接
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
private AcceptThread mAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;
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;
//構造方法,接收UI主執行緒傳遞的物件
public ChatService(Context context, Handler handler) {
//構造方法完成藍牙物件的創建
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mHandler = handler;
}
private synchronized void setState(int state) {
mState = state;
mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
}
public synchronized int getState() {
return mState;
}
public synchronized void start() {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
if (mAcceptThread == null) {
mAcceptThread = new AcceptThread();
mAcceptThread.start();
}
setState(STATE_LISTEN);
}
//取消 CONNECTING 和 CONNECTED 狀態下的相關執行緒,然后運行新的 mConnectThread 執行緒
public synchronized void connect(BluetoothDevice device) {
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
mConnectThread = new ConnectThread(device);
mConnectThread.start();
setState(STATE_CONNECTING);
}
/*
開啟一個 ConnectedThread 來管理對應的當前連接,之前先取消任意現存的 mConnectThread 、
mConnectedThread 、 mAcceptThread 執行緒,然后開啟新 mConnectedThread ,傳入當前剛剛接受的
socket 連接,最后通過 Handler來通知UI連接
*/
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
if (mAcceptThread != null) {
mAcceptThread.cancel();
mAcceptThread = null;
}
mConnectedThread = new ConnectedThread(socket);
mConnectedThread.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);
}
// 停止所有相關執行緒,設當前狀態為 NONE
public synchronized void stop() {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
if (mAcceptThread != null) {
mAcceptThread.cancel();
mAcceptThread = null;
}
setState(STATE_NONE);
}
// 在 STATE_CONNECTED 狀態下,呼叫 mConnectedThread 里的 write 方法,寫入 byte
public void write(byte[] out) {
ConnectedThread r;
synchronized (this) {
if (mState != STATE_CONNECTED)
return;
r = mConnectedThread;
}
r.write(out);
}
// 連接失敗的時候處理,通知 ui ,并設為 STATE_LISTEN 狀態
private void connectionFailed() {
setState(STATE_LISTEN);
Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(BluetoothChat.TOAST, "鏈接不到設備");
msg.setData(bundle);
mHandler.sendMessage(msg);
}
// 當連接失去的時候,設為 STATE_LISTEN 狀態并通知 ui
private void connectionLost() {
setState(STATE_LISTEN);
Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(BluetoothChat.TOAST, "設備鏈接中斷");
msg.setData(bundle);
mHandler.sendMessage(msg);
}
// 創建監聽執行緒,準備接受新連接,使用阻塞方式,呼叫 BluetoothServerSocket.accept()
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
//使用射頻埠(RF comm)監聽
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
}
mmServerSocket = tmp;
}
@Override
public void run() {
setName("AcceptThread");
BluetoothSocket socket = null;
while (mState != STATE_CONNECTED) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
if (socket != null) {
synchronized (ChatService.this) {
switch (mState) {
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();
}
}
}
/*
連接執行緒,專門用來對外發出連接對方藍牙的請求和處理流程,
建構式里通過 BluetoothDevice.createRfcommSocketToServiceRecord() ,
從待連接的 device 產生 BluetoothSocket. 然后在 run 方法中 connect ,
成功后呼叫 BluetoothChatSevice 的 connected() 方法,定義 cancel() 在關閉執行緒時能夠關閉相關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");
mAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException e) {
connectionFailed();
try {
mmSocket.close();
} catch (IOException e2) {
e.printStackTrace();
}
ChatService.this.start();
return;
}
synchronized (ChatService.this) {
mConnectThread = null;
}
connected(mmSocket, mmDevice);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
雙方藍牙連接后一直運行的執行緒;建構式中設定輸入輸出流,
run()方法中使用阻塞模式的 InputStream.read()回圈讀取輸入流,然后發送到 UI 執行緒中更新聊天訊息,
本執行緒也提供了 write() 將聊天訊息寫入輸出流傳輸至對方,傳輸成功后回寫入 UI 執行緒,最后使用cancel()關閉連接的 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();
}
}
}
}
設備顯示
public class DeviceList extends AppCompatActivity{
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
public static String EXTRA_DEVICE_ADDRESS = "device_address"; //Mac地址
//定義廣播接收者,用于處理掃描藍牙設備后的結果
private final BroadcastReceiver mReceiver = 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) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_list);
//在被呼叫活動里,設定回傳結果碼
setResult(Activity.RESULT_CANCELED);
init(); //活動界面
}
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(); //搜索藍牙設備
}
});
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
//已配對藍牙設備串列
ListView pairedListView =findViewById(R.id.paired_devices);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mPaireDeviceClickListener);
//未配對藍牙設備串列
ListView newDevicesListView = findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mNewDeviceClickListener);
//動態注冊廣播接收者
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
this.unregisterReceiver(mReceiver);
}
private void doDiscovery() {
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
mBtAdapter.startDiscovery(); //開始搜索藍牙設備并產生廣播
//startDiscovery是一個異步方法
//找到一個設備時就發送一個BluetoothDevice.ACTION_FOUND的廣播
}
private AdapterView.OnItemClickListener mPaireDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
mBtAdapter.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) {
mBtAdapter.cancelDiscovery();
Toast.makeText(DeviceList.this, "請在藍牙設定界面手動連接設備",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
startActivityForResult(intent,1);
}
};
//回呼方法:進入藍牙配對設定界面回傳后執行
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
init(); //重繪好友串列
}
}
切換主MainActivity為BluetoothChat
public class BluetoothChat<ChatService> 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; //請求連接設備
private static final int REQUEST_ENABLE_BT = 2;
private TextView mTitle;
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
private String mConnectedDeviceName = null;
private ArrayAdapter<String> mConversationArrayAdapter;
private StringBuffer mOutStringBuffer;
private BluetoothAdapter mBluetoothAdapter = null;
//TODO
private com.example.mybluetooth.ChatService mChatService = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//確認開發環境
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);
}
}
//TODO
Toolbar toolbar = findViewById(R.id.toolbar);
//創建選項選單
toolbar.inflateMenu(R.menu.option_menu);
//選項選單監聽
toolbar.setOnMenuItemClickListener(new MyMenuItemClickListener());
mTitle = findViewById(R.id.title_left_text);
mTitle.setText(R.string.app_name);
mTitle = findViewById(R.id.title_right_text);
// 得到本地藍牙配接器
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "藍牙不可用", Toast.LENGTH_LONG).show();
finish();
return;
}
if (!mBluetoothAdapter.isEnabled()) { //若當前設備藍牙功能未開啟
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT); //
} else {
if (mChatService == null) {
setupChat(); //創建會話
}
}
}
@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, "未授權,藍牙搜索功能將不可用!", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public synchronized void onResume() { //synchronized:同步方法實作排隊呼叫
super.onResume();
if (mChatService != null) {
if (mChatService.getState() == com.example.mybluetooth.ChatService.STATE_NONE) {
mChatService.start();
}
}
}
private void setupChat() {
//初始化ListView配接器
mConversationArrayAdapter = new ArrayAdapter<String>(this,R.layout.message);
mConversationView = findViewById(R.id.in);
mConversationView.setAdapter(mConversationArrayAdapter);
mOutEditText = findViewById(R.id.edit_text_out);
mOutEditText.setOnEditorActionListener(mWriteListener);
mSendButton = findViewById(R.id.button_send);
mSendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView view = findViewById(R.id.edit_text_out);
String message = view.getText().toString();
sendMessage(message);
}
});
//創建服務物件
mChatService = new com.example.mybluetooth.ChatService(this, mHandler);
mOutStringBuffer = new StringBuffer("");
}
@Override
public void onDestroy() {
super.onDestroy();
if (mChatService != null)
mChatService.stop();
}
private void ensureDiscoverable() { //修改本機藍牙設備的可見性
//打開手機藍牙后,能被其它藍牙設備掃描到的時間不是永久的
if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//設定在300秒內可見(能被掃描)
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
Toast.makeText(this, "已經設定本機藍牙設備的可見性,對方可搜索了,", Toast.LENGTH_SHORT).show();
}
}
private void sendMessage(String message) {
if (mChatService.getState() != com.example.mybluetooth.ChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
byte[] send = message.getBytes();
mChatService.write(send);
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
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) {
//軟鍵盤里的回車也能發送訊息
String message = view.getText().toString();
sendMessage(message);
}
return true;
}
};
//使用Handler物件在UI主執行緒與子執行緒之間傳遞訊息
@SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() { //訊息處理
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case com.example.mybluetooth.ChatService.STATE_CONNECTED:
mTitle.setText(R.string.title_connected_to);
mTitle.append(mConnectedDeviceName);
mConversationArrayAdapter.clear();
break;
case com.example.mybluetooth.ChatService.STATE_CONNECTING:
mTitle.setText(R.string.title_connecting);
break;
case com.example.mybluetooth.ChatService.STATE_LISTEN:
case com.example.mybluetooth.ChatService.STATE_NONE:
mTitle.setText(R.string.title_not_connected);
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("我: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName + ": "
+ readMessage);
break;
case MESSAGE_DEVICE_NAME:
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "鏈接到 " + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(),
msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
break;
}
}
};
//回傳進入好友串列操作后的數回呼方法
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//TODO
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 = mBluetoothAdapter.getRemoteDevice(address);
mChatService.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();
}
}
}
//內部類,選項選單的單擊事件處理
private class MyMenuItemClickListener implements Toolbar.OnMenuItemClickListener {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.scan:
System.out.println("------------------------------在這--------");
//啟動DeviceList這個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;
}
}
}
actvity_main.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">
<!--新版Android支持的Toolbar,對標題欄布局-->
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<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>
</androidx.appcompat.widget.Toolbar>
<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_gravity="bottom"
android:layout_weight="1" />
<Button android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/send"/>
</LinearLayout>
</LinearLayout>

option_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/scan"
android:icon="@android:drawable/ic_menu_myplaces"
android:title="@string/connect" />
<item android:id="@+id/discoverable"
android:icon="@android:drawable/ic_menu_view"
android:title="@string/discoverable" />
<item android:id="@+id/back"
android:icon="@android:drawable/ic_menu_close_clear_cancel"
android:title="@string/back" />
</menu>

device_list.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">
<TextView android:id="@+id/title_paired_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/title_paired_devices"
android:visibility="gone"
android:background="#666"
android:textColor="#fff"
android:paddingLeft="5dp" />
<ListView android:id="@+id/paired_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView android:id="@+id/title_new_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/title_other_devices"
android:visibility="gone"
android:background="#666"
android:textColor="#fff"
android:paddingLeft="5dp" />
<!--android:visibility="gone"表示不占空間的隱藏,invisible是占空間-->
<ListView android:id="@+id/new_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2" />
<Button android:id="@+id/button_scan"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/button_scan" />
</LinearLayout>
device_name.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
message.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
效果截圖
由于我的手機是 ios系統,借用了同學的手機運行


參考博客
http://www.android-doc.com/guide/topics/connectivity/bluetooth.html
https://www.jianshu.com/p/8fbbc6723a7c
https://blog.csdn.net/Eternity68/article/details/121874517?spm=1001.2014.3001.5501
http://www.wustwzx.com/as/sy/sy11.html#mk3
Git鏈接
https://gitee.com/chen-linying/bluetooth
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/380195.html
標籤:其他
上一篇:java Spring Cloud+Spring boot+mybatis企業快速開發架構之電子商務 商城原始碼 分布式商城 微服務商城原始碼
