所有的bluetooth API都在android.bluetooth package下
BluetoothAdapter
允許你查詢local的資料(ex. MAC address), 搜尋設備, 初始化連線
首先使用BluetoothAdapter的getDefaultAdaper得到local device的handle
用意在於確認local設備是否存在(or 你可以使用getAddress得到local device MAC address)
之後得到的handle就可以使用startDiscovery
官方說會預設12秒搜尋時間
你可以先註冊兩個message
ACTION_FOUND and ACTION_DISCOVERY_FINISHED
註冊用意在於
ACTION_FOUND:有找到設備的時候通知
ACTION_DISCOVERY_FINISHED: 搜尋結束的時候通知
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
此外寫個接收端
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
}
}
官方說會預設12秒搜尋時間
你可以先註冊兩個message
ACTION_FOUND and ACTION_DISCOVERY_FINISHED
註冊用意在於
ACTION_FOUND:有找到設備的時候通知
ACTION_DISCOVERY_FINISHED: 搜尋結束的時候通知
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
此外寫個接收端
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
}
}
沒有留言:
張貼留言