歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中藍牙使用步驟小結

Android中藍牙使用步驟小結

日期:2017/3/1 11:16:27   编辑:Linux編程
下面小結下Android中使用藍牙的幾個步驟

1 導入相關的包:
import android.bluetooth.*;

2 設置好權限
<uses-permission android:name="android.permission.BLUETOOTH" />

如果要更多的高級用戶權限設置,要這樣
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

3 android中有個BluetoothAdapter的單例類,首先要用到它,即
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

之後要判斷設備是否支持藍牙,可以這樣判斷
Java代碼
  1. BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); if(bluetooth != null) { }
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();   if(bluetooth != null) {     }

如果不為null,則支持

還要判斷用戶是否啟用藍牙功能:
Java代碼
  1. if (bluetooth.isEnabled()) { } else{ }
 if (bluetooth.isEnabled()) {      } else{    }


4 接下來,我們顯示個用戶,如果啟用了藍牙,則顯示藍牙設備的名和狀態
如果藍牙設備沒啟用,也告訴用戶
Java代碼
  1. String status; if (bluetooth.isEnabled()) { String mydeviceaddress = bluetooth.getAddress(); String mydevicename = bluetooth.getName(); status = mydevicename + ” : ” + mydeviceaddress; } else{ status = “Bluetooth is not Enabled.”; } Toast.makeText(this, status, Toast.LENGTH_LONG).show();
String status; if (bluetooth.isEnabled()) {     String mydeviceaddress = bluetooth.getAddress();     String mydevicename = bluetooth.getName();     status = mydevicename + ” : ” + mydeviceaddress; } else{     status = “Bluetooth is not Enabled.”; }   Toast.makeText(this, status, Toast.LENGTH_LONG).show();


這裡使用getName()獲得設備名,如果之前有打開
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

的話,可以這樣設置藍牙設備名:
bluetooth.setName("AndroidCoder");
5 顯示藍牙狀態:
String state = bluetooth.getState(); status = mydevicename + ” : ” + mydeviceaddress + " : " + state;

其中,藍牙狀態有:
STATE_TURNING_ON
STATE_ON
STATE_TURNING_OFF
STATE_OFF
Copyright © Linux教程網 All Rights Reserved