[Android development basics] Obtaining Bluetooth information (Bluetooth)

I. Introduction

  • Description: Bluetooth technology is an open global specification for wireless data and voice communications. It is a special short-range wireless technology connection that establishes a communication environment for fixed and mobile devices based on low-cost short-range wireless connections. Bluetooth enables some of today's portable mobile and computer devices to connect to the Internet without the need for cables and to provide wireless access to the Internet. It is also widely used in life, such as car Bluetooth and public washing machines.
  • Frequency band: 2.4-2.485GHz ISM band
  • Features: (Excerpt quoted from Baidu Encyclopedia)
    1. Bluetooth technology is applicable to many devices and does not require cables. It connects computers and telecommunications wirelessly for communication.
    2. The working frequency band of Bluetooth technology is universal worldwide and is suitable for unlimited use by users around the world, solving the national boundary barriers of cellular mobile phones.
    3. Bluetooth technology has strong security and anti-interference capabilities. Because Bluetooth technology has a frequency hopping function, it effectively avoids interference sources in the ISM band.
    4. At this stage, the main working range of Bluetooth technology is about 10 meters. After increasing the radio frequency power, Bluetooth technology can work within a range of 100 meters. Only in this way can the working quality and efficiency of Bluetooth be ensured during transmission and the Bluetooth technology can be improved. transmission speed.
  • Knowledge points:
    1. Bluetooth
    2. Broadcasting
  • Difficulty: Beginner
  • Effect:
    Insert image description here

2. Operation

        Because of progress issues to prevent beginners from being discouraged, this blog will only describe how to turn on Bluetooth, turn on detectable settings and search for Bluetooth. Regarding Bluetooth connection and Bluetooth communication, I will put TCP and UDP data communication together into one article. A blog for advanced intermediate difficulty.

1. Permissions

         The following permissions need to be added to AndroidManifest.xml to prevent failure to turn on Bluetooth and failure to receive reminders.

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

        Secondary judgment of the main interface.java permissions. This permission judgment needs to be added in versions above SDK23. Otherwise, after the first rejection, the reminder may not pop up again, and the user needs to manually turn on the permissions.

	private void requestPermission() {
    
    
        if (Build.VERSION.SDK_INT >= 23 && !isPermissionR){
    
    
            isPermissionR = true;
            ArrayList<String> permissionsList = new ArrayList<>();
            String[] permissions = {
    
    
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
            };
            for (String perm : permissions) {
    
    
                if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(MainActivity.this,perm)) {
    
    
                    permissionsList.add(perm);
                }
            }
            if (!permissionsList.isEmpty()) {
    
    
                String[] strings = new String[permissionsList.size()];
                ActivityCompat.requestPermissions(MainActivity.this , permissionsList.toArray(strings),0);
            }
        }
    }

2. Turn on Bluetooth

Send a request through the Intent mechanism and turn on Bluetooth.

   //获得BluetoothAdapter对象,启动API
   BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
   
   //判断本机是否有蓝牙设备
   if (bluetoothAdapter == null) {
    
    
       text.setText("本机无蓝牙设备\n");
   } else if (!bluetoothAdapter.isEnabled()) {
    
    
       //若手机蓝牙未开启,将启动蓝牙设备
       Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
       //发送请求,开启蓝牙
       startActivityForResult(intent , 300);
       bluetoothAdapter.cancelDiscovery();
       requestPermission();
   } else {
    
    
       Toast.makeText(MainActivity.this , "蓝牙已开启", Toast.LENGTH_SHORT).show();
   }

3. Detectable

Only when detectability is turned on can it be detected by other applications.

    if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
    
    
        showToast("请先开启本机蓝牙");
        return;
    }
    if (bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
    
    
        //不可被检测性
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        //使本机可在 500秒 内可被检测到
        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,500);
        startActivity(intent);
    } else {
    
    
        showToast("本机已处于被检测状态!!");
    }

4. Search Bluetooth

Here the Set method is used to obtain Bluetooth information.

    if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
    
    
        showToast("请先开启本机蓝牙");
        return;
    }
    foundInfo = "发现蓝牙设备:\n"; // 将搜索结果字符串恢复成初始值
    bluetoothAdapter.startDiscovery();
    // 收集蓝牙信息
    Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
    if(pairedDevices.size()>0)
    {
    
    
        String pairedInfo = "可配对的蓝牙设备:\n";
        for(Iterator<BluetoothDevice> it = pairedDevices.iterator(); it.hasNext();)
        {
    
    
            BluetoothDevice pairedDevice = (BluetoothDevice)it.next();
            //显示出远程蓝牙设备的名字和物理地址
            pairedInfo += pairedDevice.getName()+"  "+pairedDevice.getAddress()+"\n";
        }
        text.setText(pairedInfo);
    }

	class BluetoothReceiver extends BroadcastReceiver{
    
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
    
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
    
    
            //获得扫描到的远程蓝牙设备
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            foundInfo += device.getName()+"  "+device.getAddress()+"\n";
        }
        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
    
     //搜索结束
            if (foundInfo.equals("发现蓝牙设备:\n")) {
    
    
                Toast.makeText(MainActivity.this , "没有搜索到蓝牙设备" , Toast.LENGTH_SHORT).show();
            }
            else {
    
    
                //显示搜索结果
                text.setText(foundInfo);
                text.setMovementMethod(ScrollingMovementMethod.getInstance());
            }
        }

5. Broadcast

Broadcasting is the most important part of Bluetooth detection.

		//创建蓝牙广播信息
        bluetoothReceiver = new BluetoothReceiver();
        //设定广播接收的filter
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        //注册广播接收器,当设备被发现时调用函数
        registerReceiver(bluetoothReceiver , filter);
        //设定另一事件广播
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        //注册广播接收器
        registerReceiver(bluetoothReceiver,filter);

3. Accessories

1. UI interface design

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_kq"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="打开蓝牙"
        android:background="@drawable/shape"/>

    <Button
        android:id="@+id/btn_jcx"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="启动附近可检测"
        android:background="@drawable/shape"/>

    <Button
        android:id="@+id/btn_ss"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="搜索附近可配对"
        android:background="@drawable/shape"/>

    <TextView
        android:id="@+id/bluetooth_text"
        android:layout_width="match_parent"
        android:layout_marginTop="40dp"
        android:scrollbars="vertical"
        android:fadeScrollbars="false"
        android:layout_height="wrap_content"/>

</LinearLayout>

2. Total code

public class MainActivity extends AppCompatActivity {
    
    

    private Button btnDk,btnKj,btnSs;
    private TextView text;
    private String foundInfo = null;
    //获得BluetoothAdapter对象,启动API
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    BluetoothReceiver bluetoothReceiver;
    private boolean isPermissionR = false;

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

        init();
    }

    private void init() {
    
    
        text = findViewById(R.id.bluetooth_text);
        //开启蓝牙
        btnDk = findViewById(R.id.btn_kq);
        btnDk.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                //判断本机是否有蓝牙设备
                if (bluetoothAdapter == null) {
    
    
                    text.setText("本机无蓝牙设备\n");
                } else if (!bluetoothAdapter.isEnabled()) {
    
    
                    //若手机蓝牙未开启,将启动蓝牙设备
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    //发送请求,开启蓝牙
                    startActivityForResult(intent , 300);
                    bluetoothAdapter.cancelDiscovery();
                    requestPermission();
                } else {
    
    
                    showToast("蓝牙已开启");
                }
            }
        });

        btnKj = findViewById(R.id.btn_jcx);
        btnKj.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
    
    
                    showToast("请先开启本机蓝牙");
                    return;
                }
                if (bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
    
    
                    //不可被检测性
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                    //使本机可在 500秒 内可被检测到
                    intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,500);
                    startActivity(intent);
                } else {
    
    
                    showToast("本机已处于被检测状态!!");
                }
            }
        });

        btnSs = findViewById(R.id.btn_ss);
        btnSs.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
    
    
                    showToast("请先开启本机蓝牙");
                    return;
                }
                foundInfo = "发现蓝牙设备:\n"; //将搜索结果字符串恢复成初始值
                bluetoothAdapter.startDiscovery();
                Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
                if(pairedDevices.size()>0)
                {
    
    
                    String pairedInfo = "可配对的蓝牙设备:\n";
                    for(Iterator<BluetoothDevice> it = pairedDevices.iterator(); it.hasNext();)
                    {
    
    
                        BluetoothDevice pairedDevice = (BluetoothDevice)it.next();
                        //显示出远程蓝牙设备的名字和物理地址
                        pairedInfo += pairedDevice.getName()+"  "+pairedDevice.getAddress()+"\n";
                    }
                    text.setText(pairedInfo);
                }
            }
        });

        //创建蓝牙广播信息
        bluetoothReceiver = new BluetoothReceiver();
        //设定广播接收的filter
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        //注册广播接收器,当设备被发现时调用函数
        registerReceiver(bluetoothReceiver , filter);
        //设定另一事件广播
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        //注册广播接收器
        registerReceiver(bluetoothReceiver,filter);
    }


    class BluetoothReceiver extends BroadcastReceiver{
    
    
        @Override
        public void onReceive(Context context, Intent intent) {
    
    
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
    
    
                //获得扫描到的远程蓝牙设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                foundInfo += device.getName()+"  "+device.getAddress()+"\n";
            }
            else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
    
     //搜索结束
                if (foundInfo.equals("发现蓝牙设备:\n")) {
    
    
                    Toast.makeText(MainActivity.this , "没有搜索到蓝牙设备" , Toast.LENGTH_SHORT).show();
                }
                else {
    
    
                    //显示搜索结果
                    text.setText(foundInfo);
                    text.setMovementMethod(ScrollingMovementMethod.getInstance());
                }
            }
        }
    }

    public void showToast(String string) {
    
    
        Toast.makeText(MainActivity.this , string , Toast.LENGTH_SHORT).show();
    }

    private void requestPermission() {
    
    
        if (Build.VERSION.SDK_INT >= 23 && !isPermissionR){
    
    
            isPermissionR = true;
            ArrayList<String> permissionsList = new ArrayList<>();
            String[] permissions = {
    
    
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
            };
            for (String perm : permissions) {
    
    
                if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(MainActivity.this,perm)) {
    
    
                    permissionsList.add(perm);
                }
            }
            if (!permissionsList.isEmpty()) {
    
    
                String[] strings = new String[permissionsList.size()];
                ActivityCompat.requestPermissions(MainActivity.this , permissionsList.toArray(strings),0);
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_48916759/article/details/131232074