實驗目的
在app中實作藍牙通信
主要代碼
建立工程BlueTooth,在AndroidManifest.xml中添權重限申請
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
界面設計activity_main
<?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:background="@color/blue">
<!--新版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" >
</ListView>
<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>
編寫藍牙服務檔案
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();
}
}
}
}
Mainactivty
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide(); //隐藏标題欄
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);
//建立選項菜單
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() == ChatService.STATE_NONE) {
mChatService.start();
}
}
}
private void setupChat() {
mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.activity_main);
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 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() != 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主線程與子線程之間傳遞消息
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:
mTitle.setText(R.string.title_connected_to);
mTitle.append(mConnectedDeviceName);
mConversationArrayAdapter.clear();
break;
case ChatService.STATE_CONNECTING:
mTitle.setText(R.string.title_connecting);
break;
case ChatService.STATE_LISTEN:
case 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) {
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:
//啟動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;
}
}
}
用usb線連接配接手機并允許手機進行檔案傳送,在系統設定中打開開發者模式
android studio中顯示出你的手機後點選運作,app會自動下載下傳到手機上并運作
最終結果: