編輯:Android 開發實例
藍牙讓兩台裝置之間能無線傳輸資料。Android 平台內建了完整的藍牙框架,讓 App 可以與其他藍牙裝置交換資料。本文示範最基礎的三件事:掃描其他裝置、取得已配對裝置清單,以及透過服務探索建立連線。
所有藍牙操作都從 BluetoothAdapter 開始,透過靜態方法 getDefaultAdapter() 取得:
private BluetoothAdapter BA; BA = BluetoothAdapter.getDefaultAdapter();
要開啟裝置的藍牙,送出一個 ACTION_REQUEST_ENABLE 意圖即可。系統會跳出確認視窗讓使用者同意:
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(turnOn, 0);
除了這個常數,還有幾個常用意圖:
ACTION_REQUEST_DISCOVERABLE:讓自己的裝置進入可被发现狀態。
ACTION_STATE_CHANGED:藍牙狀態改變時發出通知。
ACTION_FOUND:每掃描到一個裝置就會送來訊息。
藍牙開啟後,呼叫 getBondedDevices() 就能拿到已配對清單,回傳的是一組 BluetoothDevice:
private Set<BluetoothDevice>pairedDevices; pairedDevices = BA.getBondedDevices();
enable():在未啟用時開啟藍牙。
isEnabled():已啟用則回傳 true。
disable():關閉藍牙。
getName():取得本機藍牙名稱。
setName(String name):變更本機藍牙名稱。
getState():取得藍牙目前的狀態。
startDiscovery():啟動為期約 120 秒的裝置探索。
這個範例做四顆按鈕,分別負責開啟、設為可見、列出配對裝置與關閉藍牙,並用一個 ListView 顯示清單。藍牙涉及硬體與權限,請務必在實機上測試。
準備工作包含建立專案、在 MainActivity 加入程式碼、配置 activity_main.xml、補上 string.xml,以及加入藍牙相關權限。
package com.example.bluetooth;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button On, Off, Visible, list;
private BluetoothAdapter BA;
private Set<BluetoothDevice>pairedDevices;
private ListView lv;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
On = (Button)findViewById(R.id.button1);
Off = (Button)findViewById(R.id.button2);
Visible = (Button)findViewById(R.id.button3);
list = (Button)findViewById(R.id.button4);
lv = (ListView)findViewById(R.id.listView1);
BA = BluetoothAdapter.getDefaultAdapter();
}
public void on(View view){
if (!BA.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(),"Turned on" ,Toast.LENGTH_LONG).show();
} else{
Toast.makeText(getApplicationContext(),"Already on", Toast.LENGTH_LONG).show();
}
}
public void list(View view){
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
Toast.makeText(getApplicationContext(),"Showing Paired Devices", Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter (this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
public void off(View view){
BA.disable();
Toast.makeText(getApplicationContext(),"Turned off" , Toast.LENGTH_LONG).show();
}
public void visible(View view){
Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible, 0);
}
@Override public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
整份版面包在 ScrollView 裡,四顆按鈕加上一個 ListView:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <ScrollView android:id="@+id/scrollView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/app_name" android:textAppearance="?android:attr/textAppearanceLarge" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="on" android:text="@string/on" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="visible" android:text="@string/Visible" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="list" android:text="@string/List" /> <Button android:id="@+id/button4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="off" android:text="@string/off" /> <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:visibility="visible" > </ListView> </LinearLayout> </ScrollView> </RelativeLayout>
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Bluetooth</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="on">Turn On</string> <string name="off">Turn Off</string> <string name="Visible">Get Visible</string> <string name="List">List Devices</string> </resources>
BLUETOOTH 用於一般通訊,BLUETOOTH_ADMIN 則是變更藍牙設定與發現狀態所需,兩者都要宣告:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.yiibai.bluetooth" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.yiibai.bluetooth.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
把實機連上電腦後選擇要執行的裝置:

App 啟動畫面:
按下開啟藍牙時,系統會先跳出詢問視窗請求同意,並不會直接打開:
按下「設為可見」,同樣會先請求權限,同意後裝置會在 120 秒內可被搜尋:
按下「列出裝置」,ListView 會呈現已配對的裝置名稱:
按下關閉後,會出現藍牙已關閉的提示:
幾個實務上的補充。從 Android 12 開始,掃描與配對需要 BLUETOOTH_SCAN、BLUETOOTH_CONNECT 這類執行期權限,舊的 BLUETOOTH_ADMIN 已不足以應付;同時 ACCESS_FINE_LOCATION 在部分版本中仍是掃描裝置的必要條件。另外,getBondedDevices() 只回傳已配對的裝置,要發現新裝置必須搭配 BluetoothDevice.ACTION_FOUND 廣播接收器,並用 createBond() 建立配對。若要傳輸資料,則需在配對之後各自開啟 BluetoothSocket 與 BluetoothServerSocket,這部分已超出本文範圍,有興趣可再往下深入。
Android 登入表單的錯誤回饋怎麼設計?Toast、剩餘次數與按鈕狀態
登入流程的成敗,往往不在「帳密對不對」,而在「錯了的時候使用者知不知道錯在哪」。一個好的登入畫面會即時告訴你三件事:帳密錯誤、還剩幾次機會、以及機會用完了。本章就用一個小
Android JSON 解析器使用教學
JSON 是 JavaScript Object Notation 的縮寫,是一種與程式語言無關的資料交換格式。憑藉著輕量、易讀的優勢,它成為 XML 以外相當主流的選擇
Android 自定義 ListView 實現左右滑動刪除與編輯
很多時候,為了滿足產品設計的交互需求,我們不得不對原生控制項進行改造。Android 原生的 ListView 並不支援左右滑動,但借鑑微信通訊錄那種「側滑顯示操作按鈕」
Chronometer 控件實現的 Android 計時器教學
本文示範使用 Chronometer 建立計時器,可設定秒數、開始、停止與重置,並在時間到時跳出提示。實作原理Chronometer 會從 setBase 設定的基準時間