android 蓝牙

本文提供了一套详细的蓝牙开发指导,包括验证设备是否支持蓝牙、连接蓝牙设备、启用蓝牙、获取已配对设备列表、设置设备为可检测状态、等待传入连接请求及远程设备发现等关键步骤。

/*

* 蓝牙

*/

 

//***验证是否支持蓝牙

 

// AndroidManifest.xml must have the following permission:

//<uses-permission android:name="android.permission.BLUETOOTH"/>

// Trying to get the adapter

BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

 

if (btAdapter == null) {

      // Bluetooth is not supported, do something here to warn the user

      return;

}

 

//***连接至设备

 

// AndroidManifest.xml must have the following permission:

//<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 application

UUID MY_UUID = UUID.fromString("yourdata");     

 

// Get the adapter

BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

 

// The socket

BluetoothSocket socket = null;

try {

    // Your app UUID string (is also used by the server) 

    socket = device.createRfcommSocketToServiceRecord(MY_UUID);

} catch (IOException e) { }

 

// For performance reasons

btAdapter.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);

 

//***启用蓝牙

 

// AndroidManifest.xml must have the following permission:

//<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 adapter

BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

 

if (btAdapter == null) {

    return;

}

  

// If Bluetooth is not yet enabled, enable it    

if (!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 

}

 

 

//***获取成对设备

 

// AndroidManifest.xml must have the following permission:

//<uses-permission android:name="android.permission.BLUETOOTH"/>

// Get the adapter

BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

 

// Get the paired devices

Set<BluetoothDevice> devices = btAdapter.getBondedDevices();

 

// If there are paired devices, do whatever you're supposed to do

if (devices.size() > 0) {

    for (BluetoothDevice pairedDevice : devices) {

        // do something useful with the device

    }

}

 

//***确保可检测此设备

 

// AndroidManifest.xml must have the following permission:

//<uses-permission android:name="android.permission.BLUETOOTH"/>

//Get the adapter

BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

 

if (btAdapter == null) {

    return;

}

 

// If Bluetooth is not discoverable, make it discoverable

if (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);

}

 

//***等待传入连接

 

// AndroidManifest.xml must have the following permission:

//<uses-permission android:name="android.permission.BLUETOOTH"/>

// UUID for your application

UUID MY_UUID = UUID.fromString("yourdata");        

 

// SDP record name used when creating the server socket

String NAME = "BluetoothExample";

 

// The server socket

BluetoothServerSocket btServerSocket =  null;

 

// The adapter

BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

 

// The socket

BluetoothSocket 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

    }                       

}

 

//***远程设备检测寄存器

 

// AndroidManifest.xml must have the following permission:

//<uses-permission android:name="android.permission.BLUETOOTH"/>

// Register for notification upon discovery of a Bluetooth device

IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

this.registerReceiver(bluetoothReceiver, intentFilter);

 

// Register for notification upon completion of the device discovery process 

intentFilter = 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 file

private 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                

        }

    }

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值