Android蓝牙详析 | 蓝牙的适配、权限、开启、搜索发现等处理

本系列笔记概述

  • 蓝牙传输优势:功耗低,传输距离还可以;

  • 蓝牙聊天室案例

  • Android中蓝牙设备的使用
    • 蓝牙权限(本文的讲解内容之一)
    • 蓝牙功能开启(本文的讲解内容之一)
    • 搜索蓝牙设备(本文的讲解内容之一)
    • 与外设搭建RFCOMM通道(射频通道)
    • 蓝牙设备双向数据传输

蓝牙聊天室案例框架

  • 蓝牙权限

    • 执行蓝牙通信需要权限BLUETOOTH,
      例如:请求连接、接收连接和传输数据等;

    • 如果需要启动设备 或 操作蓝牙设置,则需声明BLUETOOTH_ADMIN权限

    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
  • 设置蓝牙——获取BlueAdapter

    • 使用蓝牙需用到BlueAdapter。表示设备自身的蓝牙适配器;

    • 通过静态方法BlueAdapter.getDefaultAdapter()获得BlueAdapter;

    • 整个系统只有一个蓝牙适配器,application可使用此BlueAdapter对象与之交互;

    • 如果getDefaultAdapter()返回null,则表示该设备不支持蓝牙,
      例如:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter == null){
            //Device does not support Bluetooth
        }
  • 启用蓝牙

    • 调用isEnable()以检查当前是否已启用蓝牙;
      如果此方法返回false,则表示蓝牙处于停用状态;

    • 要请求启用蓝牙,将通过ACTION_REQUEST_ENABLE向系统设置
      发出启用蓝牙的请求(无需停止应用),
      例如:

...
    private static final int REQUEST_ENABLE_BT = 10;//其是需要自己定义的局部常量。
...

        if(mBluetoothAdapter.isEnabled()){
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }

demo(查看本机是否支持蓝牙,蓝牙是否开启,没开启则请求):

  • 新建一个项目,添加好如上述两个权限,编写MainActivity.java:
public class MainActivity extends AppCompatActivity {


    private static final String TAG = "BluetoothChat";
    private static final int REQUEST_ENABLE_BT = 10;//其是需要自己定义的局部常量。
    private BluetoothAdapter mBluetoothAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter == null){
            //Device does not support Bluetooth
            Log.e(TAG, "Device does not support Bluetooth");
        }else {
            Toast.makeText(this,"设备支持蓝牙!",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

        if(!mBluetoothAdapter.isEnabled()){
            //向系统请求开启蓝牙
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);//结果返回回调到onActivityResult()
        }else {
            //已经开启了蓝牙
            Toast.makeText(this,"蓝牙已经开启",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_ENABLE_BT){
            Toast.makeText(this,"蓝牙已经开启",Toast.LENGTH_SHORT).show();
        }
    }
}


  • 查找设备——查找配对过的设备

    • getBondedDevices():返回已配对设备的一组BluetoothDevice
 Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
                //If threre are paired devices
                if (pairedDevices.size() > 0) {
                    //Loop through paired devices
                    for(BluetoothDevice device : pairedDevices){
                        //Add the name and address to an array adapter to show in a ListView
                        mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    }
                }
  • 查找设备——发现设备

    • 发现设备:startDiscovery()
      该进程为异步进程,
      该方法会立即返回一个布尔值,指示是否已成功启动发现操作
    • 发现进程通常包含约12秒钟查询扫描
  1. 广播接收:
 //广播接收
    private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();//获取action
            Log.d(TAG, "ACTION:" + action);
            if(action.equals(BluetoothDevice.ACTION_FOUND)){
                //如果扫描时发现蓝牙设备,取到发现的设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);           
            }else if(action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
                //如果扫描完毕                
            }
        }
    };
  1. 广播过滤、注册、注销:
...
        //为广播接收器注册过滤器
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mBluetoothReceiver,filter);
...
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBluetoothReceiver);
    }

demo(查找已配对蓝牙,log打印出来):

续上,修改activity_main.xml:

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

    <Button
        android:id="@+id/bt_paired_device"
        android:text="已配对设备"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/bt_scan"
        android:text="扫描附近蓝牙设备"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    
</LinearLayout>

接着修改MainActivity.java:
实例化、绑定:

...
//scan paired
    private Button mScanButton;
    private  Button mPairedDeviceButton;
...
        //scan paired
        mPairedDeviceButton = (Button)findViewById(R.id.bt_paired_device);
        mScanButton = (Button)findViewById(R.id.bt_scan);
...

添加onClick:

mPairedDeviceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //paired 配对的
                Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
                //If threre are paired devices
//                if (pairedDevices.size() > 0) {
                    //Loop through paired devices
                    for(BluetoothDevice device : pairedDevices){
                        //You add the name and address to an array adapter to show in a ListView at this
                        Log.d(TAG, "Device name  " + device.getName());//打印匹配过的蓝牙设备的name
                        Log.d(TAG, "Device addr  " + device.getAddress());
                    }
//                }
            }
        });
        mScanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mBluetoothAdapter.isDiscovering()){//如果正在扫描,令之停止扫描,重新开始扫描
                    mBluetoothAdapter.cancelDiscovery();
                }
                mBluetoothAdapter.startDiscovery();//异步函数
            }
        });

运行之后点击“已配对设备”按钮,显示已配对蓝牙设备的信息:

此时java:

public class MainActivity extends AppCompatActivity {


    private static final String TAG = "BluetoothChat";
    private static final int REQUEST_ENABLE_BT = 10;//其是需要自己定义的局部常量。
    private BluetoothAdapter mBluetoothAdapter;

    //scan paired
    private Button mScanButton;
    private  Button mPairedDeviceButton;

    //广播接收

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //scan paired
        mPairedDeviceButton = (Button)findViewById(R.id.bt_paired_device);
        mScanButton = (Button)findViewById(R.id.bt_scan);
        mPairedDeviceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //paired 配对的
                Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
                //If threre are paired devices
//                if (pairedDevices.size() > 0) {
                    //Loop through paired devices
                    for(BluetoothDevice device : pairedDevices){
                        //Add the name and address to an array adapter to show in a ListView
                        Log.d(TAG, "Device name  " + device.getName());//打印匹配过的蓝牙设备的name
                        Log.d(TAG, "Device addr  " + device.getAddress());
                    }
//                }
            }
        });
        mScanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mBluetoothAdapter.isDiscovering()){//如果正在扫描,令之停止扫描,重新开始扫描
                    mBluetoothAdapter.cancelDiscovery();
                }
                mBluetoothAdapter.startDiscovery();//异步函数
            }
        });

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter == null){
            //Device does not support Bluetooth
            Log.e(TAG, "Device does not support Bluetooth");
        }else {
            Toast.makeText(this,"设备支持蓝牙!",Toast.LENGTH_SHORT).show();
        }


    }

    @Override
    protected void onStart() {
...
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
...
        }
    }
}

demo(续上,监测扫描发现设备时扫描完毕时两个状态,做对应处理):

  • 点击“扫描附近蓝牙设备”按钮时,开始一轮新的扫描:
        mScanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mBluetoothAdapter.isDiscovering()){//如果正在扫描,令之停止扫描,重新开始扫描
                    mBluetoothAdapter.cancelDiscovery();
                }
                mBluetoothAdapter.startDiscovery();//异步函数
            }
        });
  • 注册广播接收器,
    监测扫描发现设备时扫描完毕时两个状态,
    然后做对应处理:
    //广播接收
    private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();//获取action
            Log.d(TAG, "ACTION:" + action);
            if(action.equals(BluetoothDevice.ACTION_FOUND)){
                //如果扫描时发现蓝牙设备,取到发现的设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.d(TAG, "new Device name  " + device.getName());//打印匹配过的蓝牙设备的name
                Log.d(TAG, "new Device addr  " + device.getAddress());
            }else if(action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
                //如果扫描完毕
                Toast.makeText(MainActivity.this,"Discovery done!",Toast.LENGTH_SHORT).show();
                Log.d(TAG, "Discovery done!");
            }
        }
    };
  • 在onCreate()末尾注册intent过滤器:
        //为广播接收器注册过滤器
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mBluetoothReceiver,filter);
  • 在onDestroy()中注销:
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBluetoothReceiver);
    }
  • 运行效果如图,没有发现新设备,在扫描完毕后打印出对应的Log:
  • 此时java:

public class MainActivity extends AppCompatActivity {


    private static final String TAG = "BluetoothChat";
    private static final int REQUEST_ENABLE_BT = 10;//其是需要自己定义的局部常量。
    private BluetoothAdapter mBluetoothAdapter;

    //scan paired
    private Button mScanButton;
    private  Button mPairedDeviceButton;

    //广播接收
    private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();//获取action
            Log.d(TAG, "ACTION:" + action);
            if(action.equals(BluetoothDevice.ACTION_FOUND)){
                //如果扫描时发现蓝牙设备,取到发现的设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.d(TAG, "new Device name  " + device.getName());//打印匹配过的蓝牙设备的name
                Log.d(TAG, "new Device addr  " + device.getAddress());
            }else if(action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
                //如果扫描完毕
                Toast.makeText(MainActivity.this,"Discovery done!",Toast.LENGTH_SHORT).show();
                Log.d(TAG, "Discovery done!");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //scan paired
        mPairedDeviceButton = (Button)findViewById(R.id.bt_paired_device);
        mScanButton = (Button)findViewById(R.id.bt_scan);
        mPairedDeviceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //paired 配对的
                Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
                //If threre are paired devices
//                if (pairedDevices.size() > 0) {
                    //Loop through paired devices
                    for(BluetoothDevice device : pairedDevices){
                        //Add the name and address to an array adapter to show in a ListView
                        Log.d(TAG, "Device name  " + device.getName());//打印匹配过的蓝牙设备的name
                        Log.d(TAG, "Device addr  " + device.getAddress());
                    }
//                }
            }
        });
        mScanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mBluetoothAdapter.isDiscovering()){//如果正在扫描,令之停止扫描,重新开始扫描
                    mBluetoothAdapter.cancelDiscovery();
                }
                mBluetoothAdapter.startDiscovery();//异步函数
            }
        });

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter == null){
            //Device does not support Bluetooth
            Log.e(TAG, "Device does not support Bluetooth");
        }else {
            Toast.makeText(this,"设备支持蓝牙!",Toast.LENGTH_SHORT).show();
        }

        //为广播接收器注册过滤器
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mBluetoothReceiver,filter);
    }

    @Override
    protected void onStart() {
        super.onStart();

        if(!mBluetoothAdapter.isEnabled()){
            //向系统请求开启蓝牙
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);//结果返回回调到onActivityResult()
        }else {
            //已经开启了蓝牙
            Toast.makeText(this,"蓝牙已经开启",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_ENABLE_BT){
            Toast.makeText(this,"蓝牙已经开启",Toast.LENGTH_SHORT).show();
        }
    }

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





参考自,慕课网。就业班

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容

  • Guide to BluetoothSecurity原文 本出版物可免费从以下网址获得:https://doi.o...
    公子小水阅读 7,614评论 0 6
  • Android平台支持蓝牙网络协议栈,实现蓝牙设备之间数据的无线传输。本文档描述了怎样利用android平台提供的...
    Camming阅读 3,127评论 0 3
  • 蓝牙 注:本文翻译自https://developer.android.com/guide/topics/conn...
    RxCode阅读 8,461评论 11 99
  • 前言 最近在做Android蓝牙这部分内容,所以查阅了很多相关资料,在此总结一下。 基本概念 Bluetooth是...
    猫疏阅读 14,217评论 7 113
  • Android 平台包含蓝牙网络堆栈支持,凭借此项支持,设备能以无线方式与其他蓝牙设备交换数据。应用框架提供了通过...
    虎三呀阅读 743评论 0 1