相關Android藍芽知識直接略過,大家可以上百度搜搜。
此代碼經過項目驗證,完全OK
直接上代碼步驟:
private BluetoothAdapter adapter;
1.// 擷取藍芽適配器
adapter = BluetoothAdapter.getDefaultAdapter();
// 開啟藍芽
if (!adapter.isEnabled()) {
// 彈出對話方塊提示使用者選擇是否開啟藍芽
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 0);
// 或者不做提示,強行開啟
// bAdapter.enable();
}
2. 擷取藍芽MacAddress
// 搜尋並擷取已經配對藍芽
nameAddress = getPairedDevice(adapter);//變數自己添加定義
// 擷取名字列表和地址清單
if (nameAddress.size() > 0) {
blueNames = nameAddress.get(0);
blueAddress = nameAddress.get(1);
}
// 擷取方法 此處我把名字和地址分別存放到集合裡面,為了方便在ListView裡面顯示和其他用途,可以根據自己需要,或只返回地址即可
private ArrayList<ArrayList<String>> getPairedDevice(BluetoothAdapter adapter) {
ArrayList<ArrayList<String>> nameAndAddress = new ArrayList<ArrayList<String>>();
// pairedDeviceNames = new ArrayList<String>();
pairedDeviceAddress = new ArrayList<String>();
Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// 逐個解析
for (BluetoothDevice devices : pairedDevices) {
// 放到集合中
pairedDeviceNames.add(devices.getName() + "\n"
+ devices.getAddress());
pairedDeviceAddress.add(devices.getAddress());
}
// 儲存資訊
nameAndAddress.add(pairedDeviceNames);
nameAndAddress.add(pairedDeviceAddress);
}
return nameAndAddress;
}
3. 通過Address串連藍牙裝置
// 串連裝置
device = adapter.getRemoteDevice(address);
connect(device);
public synchronized void connect(BluetoothDevice device) {
connectThread = new ConnectThread(device, this, adapter, handler,handlerUpdate);
connectThread.start();
}
4. 串連藍芽線程類
public class ConnectThread extends Thread {
// 此處變數略
public ConnectThread(BluetoothDevice device, BluetoothAdapter mAdapterr) {
this.mAdapter = mAdapter;
int sdk = Build.VERSION.SDK_INT;
if (sdk >= 10) {
try {
mySocket = device
.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
mySocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void run() {
//
mAdapter.cancelDiscovery();
try {
mySocket.connect();
// 啟動接收遠程裝置發送過來的資料
connectBluetooth = new ReceiveDatas(mySocket,receiveHandler);
connectBluetooth.start();
//輸出資料流
mmOutStream = mySocket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
try {
mySocket.close();
} catch (IOException ee) {
// TODO Auto-generated catch block
ee.printStackTrace();
}
}
}
// 寫資料
/* Call this from the main Activity to send data to the remote device */
public void sendMessage(String msg) {
byte[] buffer = new byte[16];
try {
if (mmOutStream == null) {
Log.i("info", "輸出資料流為空白");
return;
}
// 寫資料
buffer = msg.getBytes();
mmOutStream.write(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (mmOutStream != null) {
mmOutStream.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
5. 讀取資料類
public class ReceiveDatas extends Thread {
// 變數 略過
// 構造方法
public ReceiveDatas(BluetoothSocket socket) {
this.mmSocket = socket;
InputStream tempIn = null;
// 擷取輸入資料流
try {
tempIn = socket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
}
mmInStream = tempIn;
}
@Override
public void run() {
byte[] buffer = new byte[1024];// 緩衝資料流
int bytes;// 返回讀取到的資料
// 監聽輸入資料流
while (true) {
try {
bytes = mmInStream.read(buffer);
// 此處處理資料……
} else {
Log.i("info", "異常");
}
} catch (IOException e) {
try {
if (mmInStream != null) {
mmInStream.close();
}
Log.i("info", "異常");
break;
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try {
Thread.sleep(50);// 延遲
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}