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

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

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

1、申请权限:




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 deviceList = new ArrayList<>();
    private Context context;

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

    public void setDeviceList(List 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 源码如下:




    

    

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

private final List bondedDeviceList = new ArrayList<>();
    
private Comparator comparator = new Comparator() {
    @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);

你可能感兴趣的:(android)