Android开发蓝牙Bluetooth的基本使用

1、先上图,再解释!

2、基本使用
2.1、检测蓝牙、打开蓝牙发现状态、输出已配对设备、扫描周边蓝牙设备;
2.2、获取当前机器蓝牙设备使用BluetoothAdapter.getDefaultAdapter()方法;
2.3、使用蓝牙设备时需要在AndroidManifest.xml中授权

1
2
<uses -permission android:name="android.permission.BLUETOOTH"></uses>
<uses -permission android:name="android.permission.BLUETOOTH_ADMIN"></uses>

前者为获取配对设备时使用,后者为扫描周边蓝牙设备时使用;
2.4、扫描蓝牙设备为异步方法,每发现一个周边设备会发送一条相关广播;
2.5、监听扫描结果需要注册广播BluetoothDevice.ACTION_FOUND

3、相关代码
activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.yusian.bluetooth.MainActivity">
 
    <TextView
        android:id="@+id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:padding="10dp"/>
 
    <Button
        android:id="@+id/btn_blue_dev"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="已配对设备"/>
    <Button
        android:id="@+id/btn_open_discover"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="打开蓝牙可见性"/>
    <Button
        android:id="@+id/btn_search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="搜索" />
 
</LinearLayout>

MainActivity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package com.yusian.bluetooth;
 
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
 
import java.util.Iterator;
import java.util.Set;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private final static String TAG = "SALog";
    private TextView textView = null;
    private BroadcastReceiver receiver = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        textView = (TextView) findViewById(R.id.tv_title);
        findViewById(R.id.btn_blue_dev).setOnClickListener(this);
        findViewById(R.id.btn_search).setOnClickListener(this);
        findViewById(R.id.btn_open_discover).setOnClickListener(this);
 
        // 注册设备扫描广播:创建建一个IntentFilter和一个BroadcastReceiver
        // BluetoothDevice.ACTION_FOUND为通知名称
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                Log.d(TAG, "onReceive: "+action);
                if (action.equals(BluetoothDevice.ACTION_FOUND)){
                    // 获取广播中关键内容,通过key取value
                    // BluetoothDevice的Key为BluetoothDevice.EXTRA_DEVICE
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    // 拼接字符串显示到文本框控件当中
                    StringBuilder string = new StringBuilder();
                    string.append(textView.getText()+"\n"+device.getAddress());
                    textView.setText(string.toString());
                }
            }
        };
        registerReceiver(receiver, filter);
    }
 
    @Override
    public void onClick(View v) {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // 如果本地无蓝牙设备则直接返回
        if (bluetoothAdapter == null){Log.d(TAG, "onClick: 无蓝牙设备!"); return;}
        // 如果蓝牙设备未打开,则弹出提示!(打开蓝牙开关!)
        if (bluetoothAdapter.isEnabled() == false) startActivity(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE));
        // 各个按钮事件处理
        switch (v.getId()){
            // 获取当前已配对设备
            case R.id.btn_blue_dev:{
                this.getContentedDevice(bluetoothAdapter);
            }break;
            // 扫描周边蓝牙设备
            case R.id.btn_search:{
                bluetoothAdapter.startDiscovery();
            }break;
            case R.id.btn_open_discover:{
                // 打开蓝牙设备可见性(打开蓝牙设备可见性!)
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500);
                startActivity(intent);
            }break;
            default:break;
        }
    }
    // 获取已配对成功的设备
    public void getContentedDevice(BluetoothAdapter bluetoothAdapter){
        // 使用Iterator遍历蓝牙设备集合
        Set<BluetoothDevice> deviceSet = bluetoothAdapter.getBondedDevices();
        Iterator iterator = deviceSet.iterator();
        StringBuilder string = new StringBuilder();
        while (iterator.hasNext()){
            BluetoothDevice bluetoothDevice = (BluetoothDevice) iterator.next();
            string.append(string + bluetoothDevice.getAddress());
        }
        if(string != null) textView.setText(string.toString());
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}

Leave a Reply