Android 常用代码---蓝牙

来源:互联网 发布:张怡宁 知乎 编辑:程序博客网 时间:2024/06/11 20:06
1验证是否支持蓝牙权限<uses-permission android:name="android.permission.BLUETOOTH"/>代码// Trying to get the adapterBluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();if (btAdapter == null) {      // Bluetooth is not supported, do something here to warn the user      return;}2连接至设备权限<uses-permission android:name="android.permission.BLUETOOTH"/>代码/* * This code is loose here but you will * likely use it inside a thread *  * Make sure you have the 'device' variable (BluetoothDevice) * at the point you insert this code */// UUID for your applicationUUID MY_UUID = UUID.fromString("yourdata"); // Get the adapterBluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();// The socketBluetoothSocket socket = null;try {    // Your app UUID string (is also used by the server)     socket = device.createRfcommSocketToServiceRecord(MY_UUID);} catch (IOException e) { }// For performance reasonsbtAdapter.cancelDiscovery();try {    // Be aware that this is a blocking operation. You probably want to use this in a thread    socket.connect();} catch (IOException connectException) {    // Unable to connect; close the socket and get out    try {     socket.close();    } catch (IOException closeException) {     // Deal with it    }    return;}// Now manage your connection (in a separate thread)myConnectionManager(socket);3启用蓝牙权限<uses-permission android:name="android.permission.BLUETOOTH"/>代码/* This number is used to identify this request ("Enable Bluetooth")  * when the callback method onActivityResult() is called. Your * interaction with the Bluetooth stack will probably start there.  *  * You probably want to insert this as a global variable  */int ENABLE_BLUETOOTH = 1;// Get the adapterBluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();if (btAdapter == null) {    return;}// If Bluetooth is not yet enabled, enable itif (!btAdapter.isEnabled()) {    Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);    startActivityForResult(enableBluetooth, ENABLE_BLUETOOTH);    // Now implement the onActivityResult() and wait for it to be invoked with ENABLE_BLUETOOTH }4获取成对设备权限<uses-permission android:name="android.permission.BLUETOOTH"/>代码// Get the adapterBluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();// Get the paired devicesSet<BluetoothDevice> devices = btAdapter.getBondedDevices();// If there are paired devices, do whatever you're supposed to doif (devices.size() > 0) {    for (BluetoothDevice pairedDevice : devices) {        // do something useful with the device    }}5确保可检测此设备权限<uses-permission android:name="android.permission.BLUETOOTH"/>代码//Get the adapterBluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();if (btAdapter == null) {     return;}// If Bluetooth is not discoverable, make it discoverableif (btAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { Intent makeDiscoverable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);    makeDiscoverable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500); // In a real situation you would probably use startActivityForResult to get the user decision.    startActivity(makeDiscoverable);}6等待传入连接权限<uses-permission android:name="android.permission.BLUETOOTH"/>代码// UUID for your applicationUUID MY_UUID = UUID.fromString("yourdata"); // SDP record name used when creating the server socketString NAME = "BluetoothExample";// The server socketBluetoothServerSocket btServerSocket =  null;// The adapterBluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();// The socketBluetoothSocket socket = null;try { btServerSocket = btAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID); // This operation is blocking: you will wait until it returns on an error occurs    socket = btServerSocket.accept();} catch (IOException e) { } // Deal with it}if (socket != null) { /* The connection was accepted. Do what you want to do. * For example, get the streams  */    InputStream inputStream = null;    OutputStream outputStream = null;    try {        inputStream = socket.getInputStream();        outputStream = socket.getOutputStream();    } catch (IOException e) {        // Deal with it    }  }7远程设备检测寄存器权限 <uses-permission android:name="android.permission.BLUETOOTH"/>代码// Register for notification upon discovery of a Bluetooth deviceIntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);this.registerReceiver(bluetoothReceiver, intentFilter);// Register for notification upon completion of the device discovery processintentFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);this.registerReceiver(bluetoothReceiver, intentFilter);// BroadcastReceiver that is notified as each device is found and when the discovery process completes // Should be an internal class or in a separate .java fileprivate final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {    @Override    public void onReceive(Context context, Intent intent) {        String action = intent.getAction();        // Device was discovered        if (BluetoothDevice.ACTION_FOUND.equals(action)) {            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);            if (device.getBondState() != BluetoothDevice.BOND_BONDED) {                // device is not already paired. Do something useful here.            }        // Discovery is finished        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {         // do something useful here            }    }};
原创粉丝点击