• Android Video Tutorials

Android - 藍牙



藍牙是眾多方法中的一種,用於在兩個不同的裝置之間傳送或接收資料。Android 平臺包含對藍牙框架的支援,允許裝置與其他藍牙裝置進行無線資料交換。

Android 提供藍牙 API 來執行這些不同的操作。

  • 掃描其他藍牙裝置

  • 獲取已配對裝置列表

  • 透過服務發現連線到其他裝置

Android 提供 BluetoothAdapter 類來與藍牙通訊。透過呼叫靜態方法 getDefaultAdapter() 建立此類的物件。其語法如下所示。

private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();

為了啟用裝置的藍牙,請使用以下藍牙常量 ACTION_REQUEST_ENABLE 呼叫意圖。其語法為:

Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);       

除了此常量外,API 還提供了其他支援不同任務的常量。它們列在下面。

序號 常量和描述
1

ACTION_REQUEST_DISCOVERABLE

此常量用於開啟藍牙的可發現性。

2

ACTION_STATE_CHANGED

此常量將通知藍牙狀態已更改。

3

ACTION_FOUND

此常量用於接收關於每個已發現裝置的資訊。

啟用藍牙後,您可以透過呼叫 getBondedDevices() 方法獲取已配對裝置的列表。它返回一組藍牙裝置。其語法為:

private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();

除了已配對的裝置外,API 中還有其他方法可以更好地控制藍牙。它們列在下面。

序號 方法和描述
1

enable()

如果未啟用,此方法將啟用介面卡。

2

isEnabled()

如果介面卡已啟用,此方法返回 true。

3

disable()

此方法停用介面卡。

4

getName()

此方法返回藍牙介面卡的名稱。

5

setName(String name)

此方法更改藍牙名稱。

6

getState()

此方法返回藍牙介面卡的當前狀態。

7

startDiscovery()

此方法啟動藍牙的發現過程,持續 120 秒。

示例

此示例演示瞭如何使用 BluetoothAdapter 類來操作藍牙並顯示藍牙已配對裝置的列表。

要試驗此示例,您需要在實際裝置上執行它。

步驟 描述
1 您將使用 Android Studio 建立一個 Android 應用,包名為 com.example.sairamkrishna.myapplication。
2 修改 src/MainActivity.java 檔案以新增程式碼。
3 修改佈局 XML 檔案 res/layout/activity_main.xml,如果需要,新增任何 GUI 元件。
4 修改 AndroidManifest.xml 以新增必要的許可權。
5 執行應用程式,選擇正在執行的 Android 裝置,將應用程式安裝在其上並驗證結果。

以下是 **src/MainActivity.java** 的內容:

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends Activity  {
   Button b1,b2,b3,b4;
   private BluetoothAdapter BA;
   private Set<BluetoothDevice>pairedDevices;
   ListView lv;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      b1 = (Button) findViewById(R.id.button);
      b2=(Button)findViewById(R.id.button2);
      b3=(Button)findViewById(R.id.button3);
      b4=(Button)findViewById(R.id.button4);

      BA = BluetoothAdapter.getDefaultAdapter();
      lv = (ListView)findViewById(R.id.listView);
   }

   public void on(View v){
      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 off(View v){
      BA.disable();
      Toast.makeText(getApplicationContext(), "Turned off" ,Toast.LENGTH_LONG).show();
   }

    
   public  void visible(View v){
      Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
      startActivityForResult(getVisible, 0);
   }

    
   public void list(View v){
      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);
   }
}

以下是 **activity_main.xml** 的內容:

此處 abc 指示 tutorialspoint 的徽標。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" 
   android:layout_width="match_parent"
   android:layout_height="match_parent" 
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context=".MainActivity"
   android:transitionGroup="true">
   
   <TextView android:text="Bluetooth Example" 
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:theme="@style/Base.TextAppearance.AppCompat" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Turn On"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_toStartOf="@+id/imageView"
      android:layout_toLeftOf="@+id/imageView"
      android:clickable="true"
      android:onClick="on" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Get visible"
      android:onClick="visible"
      android:id="@+id/button2"
      android:layout_alignBottom="@+id/button"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="List devices"
      android:onClick="list"
      android:id="@+id/button3"
      android:layout_below="@+id/imageView"
      android:layout_toRightOf="@+id/imageView"
      android:layout_toEndOf="@+id/imageView" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="turn off"
      android:onClick="off"
      android:id="@+id/button4"
      android:layout_below="@+id/button"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true" />
      
   <ListView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/listView"
      android:layout_alignParentBottom="true"
      android:layout_alignLeft="@+id/button"
      android:layout_alignStart="@+id/button"
      android:layout_below="@+id/textView2" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Paired devices:"
      android:id="@+id/textView2"
      android:textColor="#ff34ff06"
      android:textSize="25dp"
      android:layout_below="@+id/button4"
      android:layout_alignLeft="@+id/listView"
      android:layout_alignStart="@+id/listView" />

</RelativeLayout>

以下是 **strings.xml** 的內容:

<resources>
   <string name="app_name">My Application</string>
</resources>

以下是 **AndroidManifest.xml** 的內容:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >
   <uses-permission android:name="android.permission.BLUETOOTH"/>
   <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
   
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name=".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>

讓我們嘗試執行您的應用程式。我假設您已將您的實際 Android 手機裝置連線到您的計算機。要從 Android Studio 執行應用程式,請開啟專案中的一個 activity 檔案,然後單擊工具欄中的執行 Eclipse Run Icon 圖示。如果您的藍牙未開啟,它將請求您允許啟用藍牙。

Anroid Bluetooth Tutorial

現在只需選擇“獲取可見性”按鈕即可開啟您的可見性。隨後將出現以下螢幕,詢問您是否允許打開發現 120 秒。

Anroid Bluetooth Tutorial

現在只需選擇“列出裝置”選項。它將在列表檢視中列出已配對的裝置。在我的情況下,我只有一個已配對的裝置。如下所示。

Anroid Bluetooth Tutorial

現在只需選擇“關閉”按鈕即可關閉藍牙。關閉藍牙時,將出現以下訊息,指示藍牙已成功關閉。

Anroid Bluetooth Tutorial
廣告