蓝牙bluetooth

以开启/关闭/扫描配对/传输简单数据为例

添加权限:

<!-- 用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- 用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />

打开蓝牙

//TODO 1: 打开蓝牙
    Intent intent = new Intent();
    intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);// 可用
    intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); // 能被扫描
    intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200); //允许时间(可以不设置)
    startActivityForResult(intent,OPEN_CODE);

关闭蓝牙

// TODO 获取 本机蓝牙设备
manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
bluetoothAdapter = manager.getAdapter();
bluetoothAdapter.startDiscovery();

获取配对的设备

Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices(); // 获取已配对的设备
// listView展示
list_bond.addAll(bondedDevices);// 数据源 添加
adapter_bond.notifyDataSetChanged(); // 刷新适配器

扫描附近

需要用到广播
系统自动发送广播,只需要通过匹配相同的频道,通过广播接收扫描到的设备

BluetoothDevice.ACTION_FOUND 蓝牙设定相同频道

bluetoothAdapter.startDiscovery();// 开始扫描

MyReceiver代码

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){ // 找到一个远程设备
            BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // 获取扫描的设备
            MainActivity.list_discovery.add(bluetoothDevice); // 添加数据源
            MainActivity.adapter_discovery.notifyDataSetChanged(); // 刷新适配器
        }
    }
}

注册广播

MyReceiver myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(myReceiver,intentFilter);

数据的传输

首先是客户端发送客户

UUID uuid = UUID.fromString(“00001106-0000-1000-8000-00805F9B34FB”);

  // 点击配对的条目 传输 数据
        lv_bond.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice device = list_bond.get(position);
                try {
                    BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
                    socket.connect(); // 连接
                    if (socket.isConnected()){ // 判断是否连接成功
                        OutputStream outputStream = socket.getOutputStream();
                        outputStream.write("辛巴是个勇敢的小狮子".getBytes());
                        Toast.makeText(MainActivity.this, "发送成功!", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(MainActivity.this, "链接失败", Toast.LENGTH_SHORT).show();
                    }

                } catch (IOException e) {
                    Toast.makeText(MainActivity.this, "链接失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

服务端

try {
    BluetoothServerSocket serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(bluetoothAdapter.getName(), uuid);
    // 调用连接
    BluetoothSocket socket = serverSocket.accept();
    // 接受发送消息
    InputStream inputStream = socket.getInputStream();
    byte[] bys = new byte[1024];
    int read = inputStream.read(bys);
    String s = new String(bys, 0, read);
    Toast.makeText(this, ""+s, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
    e.printStackTrace();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值