Android Bluetooth使用詳解

來源:互聯網
上載者:User

1.判斷是否支援Bluetooth
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter == null) {
    //the device doesn't support bluetooth
} else {
    //the device support bluetooth
}

2.如果支援,開啟Bluetooth

if(!bluetoothAdapter.isEnable()) {
    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableIntent,REQUEST_ENABLE_BT);
}

3.監視Bluetooth開啟狀態

BroadcastReceiver bluetoothState = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
    String stateExtra = BluetoothAdapter.EXTRA_STATE;
       int state = intent.getIntExtra(stateExtra, -1);
       switch(state) {
    case BluetoothAdapter.STATE_TURNING_ON:
        break;
    case BluetoothAdapter.STATE_ON:
        break;
    case BluetoothAdapter.STATE_TURNING_OFF:
        break;
    case BluetoothAdapter.STATE_OFF:
        break;
    }
    }
}

registerReceiver(bluetoothState,new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));

4.設定本地裝置可以被其它裝置搜尋
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(discoveryIntent,REQUEST_DISCOVERY);

BroadcastReceiver discovery = new BroadcastReceiver() {
    @Override
    public void onRecevie(Content context, Intent intent) {
        String scanMode = BluetoothAdapter.EXTRA_SCAN_MODE;
        String preScanMode = BluetoothAdapter.EXTRA_PREVIOUS_SCAN_MODE;
        int mode = intent.getIntExtra(scanMode);
    }
}

registerReceiver(discovery,new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);

5.搜尋裝置
開始搜尋 bluetoothAdapter.startDiscovery();
停止搜尋 bluetoothAdapter.cancelDiscovery();

當發現一個裝置時,系統會發出ACTION_FOUND廣播訊息,我們可以實現接收這個訊息的BroadcastReceiver

BroadcastReceiver deviceFound = new BroadcastReceiver() {
    @Override
    public void onReceiver(Content content, Intent intent) {
        String remoteDeviceName = intent.getStringExtra(BluetoothAdapter.EXTRA_NAME);
        BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothAdapter.EXTRA_DEVICE);
    }
}

registerReceiver(deviceFound, new IntentFilter(BluetoothAdapter.ACTION_FOUND);

摘自:zzqLivecn的專欄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.