Android 蓝牙开发介绍

本文详细介绍了在Android系统中使用蓝牙2.0进行开发的全过程,包括权限配置、获取蓝牙适配器、开启蓝牙、搜索设备、链接设备等关键步骤,并通过实例展示了如何实现设备间的连接和数据传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Android系统中,从Android 2.0的sdk就开始支持蓝牙开发,到现在蓝牙协议已经发生了从1.0-4.2的变化,开发的过程也发生了不少的变化。这次我主要介绍蓝牙2.0开发。

Android中蓝牙2.0开发分为步骤包括

  1. 在AndroidMainfilest.xml文件中进行权限配置,具体权限如下

<!-- 允许程序链接到以配对的蓝牙设备 -->
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <!-- 打开搜索蓝牙权限 -->
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

2. 得到蓝牙适配器

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();// 获取蓝牙适配器

3. 打开蓝牙

if(!mAdapter.isEnabled()){

Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enabler, REQUEST_ENABLE)

}

4.加入搜索的结果的广播

 // 增加过滤器
        filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);// 远程设备发现动作。
        // filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//
        // 远程设备的键态的变化动作。
        // filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);//
        // 蓝牙扫描本地适配器模改变动作。
        // filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);// 状态改变动作
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        // 发送广播
        registerReceiver(receiver, filter);


private BroadcastReceiver receiver = new BroadcastReceiver() {
      @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice bluetoothDevice = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (bluetoothDevice.getBondState() != BluetoothDevice.BOND_BONDED) {
                    Map<String, Object> haspmap = new HashMap<>();
                    haspmap.put(blueName, bluetoothDevice.getName());
                    haspmap.put(blueMac, bluetoothDevice.getAddress());
                    haspmap.put(bluePaired, "");
                    int j = 1;
                    for (int i = 0; i < mPairedList.size(); i++) {
                        /*
                         * String name = mPairedList.get(i).get(blueName)
                         * .toString();
                         */
                        String mac = (String) mPairedList.get(i).get(blueMac);
                         if (!TextUtils.equals(mac, bluetoothDevice.getAddress())) {
                            continue;
                        }
                        j = 0;
                    }
                    if (j != 0) {
                        mPairedList.add(haspmap);
                    }
                    mPairedDeviceAdapter.notifyDataSetChanged();
                }
                // 结束
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                seekAnimImageView.clearAnimation();
                seekAnimImageView.setVisibility(View.GONE);
                isflag = false;
                if (mPairedDeviceAdapter.getCount() == 0) {
                    no_paired_devices.setText(R.string.no_paired_device);
                }
            } else if (!BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                if (!BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                    if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
                        BluetoothDevice bluetoothDevice = intent
                                .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        if (devicesBluetoothDevices.size() <= 0) {
                            no_paired_devices.setText(R.string.no_paired_device);
                        } else {
                            // mPairedList.clear();
                            for (BluetoothDevice iterable : devicesBluetoothDevices) {
                                Map<String, Object> haspmap = new HashMap<>();
                                haspmap.put(blueName, iterable.getName());
                                haspmap.put(blueMac, iterable.getAddress());
                                if (!bluetoothDevice.getAddress().equals(iterable.getAddress())) {
                                    haspmap.put(bluePaired, context.getString(R.string.paired));
                                    mPairedList.add(haspmap);
                                } else if (flag) {
                                    haspmap.put(bluePaired, context.getString(R.string.connected));
                                    mPairedList.add(0, haspmap);
                                }
                            }
                            mPairedDeviceAdapter.notifyDataSetChanged();
                      }
                    }
                } 
            } 
        }
    };

5. 搜索设备

 if (adapter.isDiscovering()) {
                        adapter.cancelDiscovery();
                        adapter.startDiscovery();
                    } else {
                        adapter.startDiscovery();
                    }

6.链接设备

设备连接的UUID

private static final UUID MY_UUID_SECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

客户端

//链接前首先将搜索记得关掉,这个会消耗资源的占用

a) 链接

BluetoothSocket mmSocket= device.createRfcommSocketToServiceRecord(CustomBluetoothManager.MY_UUID_SECURE);

if (!this.mmSocket.isConnected()) {
this.mmSocket.connect();
}

b)得到数据流

收数据一般是专门启动一个线程用于

private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream
private final OutputStream mmOutStream;
private boolean isClose = false;
public ConnectedThread(BluetoothSocket socket, String socketType) {
// Log.d("BluetoothService", "create ConnectedThread: " +
// socketType);
this.mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
// Log.e("BluetoothService", "temp sockets not created", e);
}
this.mmInStream = tmpIn;
this.mmOutStream = tmpOut;

}
public void run() {
byte[] buffer = new byte[512];
byte[] cmd = new byte[512];
int bytes = 0;
int index = 0;
while (!this.isClose)
try {
//得到数据流方法

bytes = this.mmInStream.read(buffer);

} catch{

}finally{

try {
this.isClose = true;
if (this.mmSocket != null) {
this.mmSocket.close();
}
} catch (IOException e) {
// Log.e("BluetoothService", "close() of connect socket failed",
// e);
Log.i("BluetoothSocket", "BluetoothSocket4");
}

}

}

//写入方法

public boolean write(byte[] buffer) {
try {
this.mmOutStream.write(buffer);
return true;
} catch (IOException e) {
// Log.e("BluetoothService", "Exception during write", e);
}
return false;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值