Android 应用开发-蓝牙开关控制及设备扫描并展示

前言:点击积累,贵在坚持,感谢你的阅览

页面基本布局如下图所示,Switch 开关控制蓝牙开启和关闭,左右两个列表展示已连接的蓝牙设备和未连接的蓝牙设备,每个设备只展示名字和地址,如果没有则展示null

1、申请权限:

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

2、在进去页面执行 onCreate生命周期时,进行权限检查,如果没有授权,则退出界面,保证后续代码执行是合法的

private static String[] PERMISSIONS = {
    "android.permission.BLUETOOTH",
    "android.permission.BLUETOOTH_ADMIN",
    "android.permission.ACCESS_FINE_LOCATION",
    "android.permission.ACCESS_COARSE_LOCATION"
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    checkPermission();
}

private void checkPermission() {
    for(String permission : PERMISSIONS) {
        if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
            showtoast("请开通相关权限,否则无法正常使用本应用!");
            ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_CODE);
            break;
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        //权限的申请结果返回
        case REQUEST_CODE: {
            boolean isAllPermissionPass = true;
            for(String permission : PERMISSIONS) {
                if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    isAllPermissionPass = false;
                    break;
                }
            }
            if (isAllPermissionPass) {
                showtoast("授权成功!");
            } else {
                finish();
            }
        }
    }
}

private void showtoast(String content) {
    Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
}

3、蓝牙开关的控制

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
    //当前设备不支持蓝牙功能
}
bluetoothAdapter.enable();//打开蓝牙
bluetoothAdapter.disable();//关闭蓝牙
bluetoothAdapter.isEnabled()//返回蓝牙开关状态,true:开启,false:关闭
bluetoothAdapter.startDiscovery();//开始扫描蓝牙设备

4、注册蓝牙相关的广播接收器

private BluetoothBroadcastReceive bluetoothBroadcastReceive;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initAndRegisterReceiver()
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(bluetoothBroadcastReceive);
}

private void initAndRegisterReceiver() {
    bluetoothBroadcastReceive = new BluetoothBroadcastReceive();
    IntentFilter intentFilter = new IntentFilter();
    //设备被发现
    intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
    //搜索开始
    intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    //搜索结束
    intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    //监视蓝牙关闭和打开的状态
    intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    //监视蓝牙设备与APP连接的状态
    intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    //蓝牙配对
    intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    //注册广播
    registerReceiver(bluetoothBroadcastReceive, intentFilter);
}

private class BluetoothBroadcastReceive extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        switch (action) {
            case BluetoothDevice.ACTION_FOUND:
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                    //已配对设备
                } else {
                    //未配对设备
                }
                break;
            case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
                showtoast("开始搜索...");
                break;
            case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                showtoast("搜索完成");
                break;
            case BluetoothAdapter.ACTION_STATE_CHANGED:
                int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                switch (blueState) {
                    case BluetoothAdapter.STATE_TURNING_ON:
                        showtoast("蓝牙正在打开");
                        break;
                    case BluetoothAdapter.STATE_ON:
                        showtoast("蓝牙已经打开");
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        showtoast("蓝牙正在关闭");
                        break;
                    case BluetoothAdapter.STATE_OFF:
                        showtoast("蓝牙已经关闭");
                        break;
                }
                break;
            case BluetoothDevice.ACTION_ACL_CONNECTED:
                BluetoothDevice b1 = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                showtoast("蓝牙设备已连接:" + b1.getName());
                break;
            case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                BluetoothDevice b2 = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                showtoast("蓝牙设备已断开:" + b2.getName() + "," + b2.getAddress());
                break;
            case BluetoothDevice.ACTION_BOND_STATE_CHANGED:
                BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                switch (bluetoothDevice.getBondState()) {
                    case BluetoothDevice.BOND_BONDED:
                        showtoast("配对完成");
                        break;
                    case BluetoothDevice.BOND_BONDING:
                        showtoast("正在配对");
                        break;
                    case BluetoothDevice.BOND_NONE:
                        showtoast("取消配对");
                        break;
                }
                break;
        }
    }
}

5、蓝牙列表展示我用的是ListView,其适配器如下:

package com.sunway.bluetoothapplication;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class BluetoothListAdapter extends BaseAdapter {
    private final List<BluetoothDevice> deviceList = new ArrayList<>();
    private Context context;

    public BluetoothListAdapter(Context context) {
        this.context = context;
    }

    public void setDeviceList(List<BluetoothDevice> deviceList) {
        this.deviceList.clear();
        this.deviceList.addAll(deviceList);
    }

    @Override
    public int getCount() {
        return deviceList.size();
    }

    @Override
    public Object getItem(int position) {
        return deviceList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        BluetoothViewHolder bluetoothViewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.bluetootn_item, null);
            bluetoothViewHolder = new BluetoothViewHolder(convertView);
            convertView.setTag(bluetoothViewHolder);
        } else {
            bluetoothViewHolder = (BluetoothViewHolder) convertView.getTag();
        }
        bluetoothViewHolder.name.setText("名字:" + deviceList.get(position).getName());
        bluetoothViewHolder.address.setText("地址:" + deviceList.get(position).getAddress());
        return convertView;
    }

    private class BluetoothViewHolder {
        TextView name;
        TextView address;

        public BluetoothViewHolder(View itemView) {
            name = itemView.findViewById(R.id.name);
            address = itemView.findViewById(R.id.address);
        }
    }
}

上面适配器中用到的layout/bluetootn_item.xml 源码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textColor="#ff0000"/>

    <TextView
        android:id="@+id/address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

6、让名字不为空的蓝牙设备展示在前面,只需要对设备集合做一个简单的排序比较,其比较器可以这样写:

private final List<BluetoothDevice> bondedDeviceList = new ArrayList<>();
    
private Comparator<BluetoothDevice> comparator = new Comparator<BluetoothDevice>() {
    @Override
    public int compare(BluetoothDevice o1, BluetoothDevice o2) {
        if (o1.getName() == null && o2.getName() != null) {
            return 1;
        }
        if (o1.getName() != null && o2.getName() == null) {
            return -1;
        }
        if (o1.getName() == null && o2.getName() == null) {
            return 0;
        }
        return 0;
    }
};

bondedDeviceList.sort(comparator);

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

却染人间愁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值