Android Studio开发学习(八、蓝牙设备连接)

引言

        上篇我们介绍了整体蓝牙模块的基本写法Android Studio开发学习(七、蓝牙模块java)-CSDN博客,当然我们检测到蓝牙设备肯定会连接蓝牙,那么如何实现蓝牙连接呢,这篇博客将实现这个功能。

 设备连接

        connectDevice 方法用于在后台线程中尝试连接到指定的蓝牙设备,并在连接成功或失败时显示相应的提示信息。成功时显示“连接成功”的提示并跳转到新 Activity,失败时显示“连接失败”的提示,使用唯一的UUID标识蓝牙服务,并确保UI更新在主线程中完成。

连接成功:

连接失败:

弹窗提示

        我们在上篇博客基础上增加部分代码,使用 AlertDialog 来显示连接状态。先来介绍一下AlertDialog :

        AlertDialog 是 Android 中用于显示警告信息、提示用户操作或要求用户确认操作的对话框组件。它可以显示标题、消息、按钮,甚至是自定义视图。AlertDialog 是通过 AlertDialog.Builder 类来构建和显示的。下面是一个显示简单的消息对话框例子:

new AlertDialog.Builder(context)
    .setTitle("标题")
    .setMessage("消息对话框")
    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // 用户点击确定按钮后的操作
        }
    })
    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // 用户点击取消按钮后的操作
        }
    })
    .show();

 蓝牙模块中的 AlertDialog 应用:

实机演示

完整代码

BlueToothActivity.java

package com.example.login.BlueTooth;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.example.login.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

public class BlueToothActivity extends AppCompatActivity {
    // 实例化蓝牙控制器
    public BlueToothController btController = new BlueToothController();
    // 蓝牙权限列表
    public ArrayList<String> requestList = new ArrayList<>();
    // 弹窗
    private Toast mToast;
    public ArrayAdapter adapter1;
    // 定义一个列表,存蓝牙设备地址,用于显示。
    public ArrayList<String> device = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth);
        // 获取ListView组件
        ListView listView = findViewById(R.id.listView1);
        // 实例化ArrayAdapter对象
        adapter1 = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, device);
        // 添加到ListView组件中
        listView.setAdapter(adapter1);
        // ListView的列表点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SuppressLint("MissingPermission")
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                CharSequence content = ((TextView) view).getText();
                // 获取蓝牙的名称和地址
                String con = content.toString();
                // 换行为切割
                String[] conArray = con.split("\n");
                // 获取蓝牙地址
                String rightStr = conArray[1].substring(5);
                BluetoothDevice device1 = btController.find_device(rightStr);
                connectDevice(device1);
            }
        });

        Button open_Bt = findViewById(R.id.openBT);
        open_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                turnOnBt();
            }
        });

        Button close_Bt = findViewById(R.id.closeBT);
        close_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getPermision();
                // 关闭蓝牙
                btController.turnOffBlueTooth();
            }
        });

        Button state_Bt = findViewById(R.id.stateBT);
        state_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getPermision();
                // 判断当前蓝牙状态
                boolean ret = btController.getBlueToothStatus();
                // 弹窗显示结果
                showToast("当前蓝牙状态:" + ret);
            }
        });

        Button update_list = findViewById(R.id.updateList);
        update_list.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("MissingPermission")
            @Override
            public void onClick(View view) {
                getPermision();
                // 初始化列表
                device.clear();
                adapter1.notifyDataSetChanged();
                // 获取已绑定蓝牙列表
                ArrayList<BluetoothDevice> bluetoothDevices = btController.getBondedDeviceList();
                // 更新列表
                for (BluetoothDevice device1 : bluetoothDevices) {
                    if (device1.getBondState() == BluetoothDevice.BOND_BONDED) {
                        device.add("设备名:" + device1.getName() + "\n" + "设备地址:" + device1.getAddress());
                    } else {
                        device.add("设备名:" + device1.getName() + "\n" + "设备地址:" + device1.getAddress() + "\n" + "连接状态:未知");
                    }
                    adapter1.notifyDataSetChanged();
                }
            }
        });
    }

    @SuppressLint("MissingPermission")
    private void connectDevice(final BluetoothDevice device) {
        final UUID MY_UUID = UUID.randomUUID();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID);
                    socket.connect();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showAlert("连接成功", "设备名:" + device.getName() + "\n设备地址:" + device.getAddress());
                            // 跳转到新Activity
                            Intent intent = new Intent(BlueToothActivity.this, DataActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("deviceAddr", device.getAddress());
                            intent.putExtras(bundle);
                            startActivity(intent);
                            finish();
                        }
                    });
                } catch (IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showAlert("连接失败", "设备名:" + device.getName() + "\n设备地址:" + device.getAddress());
                        }
                    });
                }
            }
        }).start();
    }

    private void showAlert(String title, String message) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton("确定", null)
                .show();
    }

    public static class BlueToothController {
        private BluetoothAdapter BtAdapter;
        
        public BlueToothController() {
            // 获取本地的蓝牙适配器
            BtAdapter = BluetoothAdapter.getDefaultAdapter();
        }

        @SuppressLint("MissingPermission")
        // 打开蓝牙
        public void turnOnBlueTooth(Activity activity, int requestCode) {
            if (!BtAdapter.isEnabled()) {
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                activity.startActivityForResult(intent, requestCode);
            }
        }

        @SuppressLint("MissingPermission")
        // 关闭蓝牙
        public void turnOffBlueTooth() {
            if (BtAdapter.isEnabled()) {
                BtAdapter.disable();
            }
        }

        // 获取蓝牙状态
        public boolean getBlueToothStatus() {
            // 断言,避免BtAdapter为null导致return出错
            assert (BtAdapter != null);
            // 蓝牙状态
            return BtAdapter.isEnabled();
        }

        @SuppressLint("MissingPermission")
        // 获取设备信息
        public ArrayList<BluetoothDevice> getBondedDeviceList() {
            return new ArrayList<>(BtAdapter.getBondedDevices());
        }

        // 根据蓝牙地址找到相应的设备
        public BluetoothDevice find_device(String addr) {
            return BtAdapter.getRemoteDevice(addr);
        }
    }

    public void turnOnBt() {
        getPermision();
        // 打开蓝牙
        btController.turnOnBlueTooth(this, 1);
    }

  
    public void getPermision() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            requestList.add(Manifest.permission.BLUETOOTH_SCAN);
            requestList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
            requestList.add(Manifest.permission.BLUETOOTH_CONNECT);
            requestList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            requestList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            requestList.add(Manifest.permission.BLUETOOTH);
        }
        if (requestList.size() != 0) {
            ActivityCompat.requestPermissions(this, requestList.toArray(new String[0]), 1);
        }
    }

    public void showToast(String text) {
        // 若Toast控件未初始化
        if (mToast == null) {
            // 则初始化
            mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        } else {
            // 修改显示文本
            mToast.setText(text);
        }
        // 显示
        mToast.show();
    }
}

activity_bluetooth.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    android:background="@drawable/background1"
    tools:context=".BlueTooth.BlueToothActivity">


    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="136dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toTopOf="@+id/listView1"
        app:layout_constraintGuide_end="206dp"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/openBT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="打开蓝牙"
        app:layout_constraintBottom_toTopOf="@+id/stateBT"
        app:layout_constraintEnd_toStartOf="@id/guideline1"
        app:layout_constraintHorizontal_bias="0.567"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/closeBT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="关闭蓝牙"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.473"
        app:layout_constraintStart_toEndOf="@id/guideline1"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/stateBT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="蓝牙状态"
        app:layout_constraintEnd_toStartOf="@id/guideline1"
        app:layout_constraintHorizontal_bias="0.567"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/openBT" />

    <Button
        android:id="@+id/updateList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="更新列表"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.473"
        app:layout_constraintStart_toEndOf="@id/guideline1"
        app:layout_constraintTop_toBottomOf="@id/closeBT" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="307dp"
        android:layout_height="46dp"
        android:layout_marginTop="92dp"
        android:background="#2196F3"
        android:gravity="center"
        android:text="蓝牙列表"
        android:textSize="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.495"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/stateBT" />
    <ListView
        android:id="@+id/listView1"
        android:layout_width="332dp"
        android:layout_height="350dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.491"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/textView1"
        app:layout_constraintVertical_bias="0.316" />

</androidx.constraintlayout.widget.ConstraintLayout>
  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Android Studio可以用于开发蓝牙应用程序。在Android Studio中,可以使用BluetoothAdapter类来管理蓝牙连接,使用BluetoothSocket类来建立蓝牙连接,使用BluetoothDevice类来表示蓝牙设备开发蓝牙应用程序需要了解蓝牙协议栈和蓝牙通信协议,以及如何处理蓝牙设备连接和数据传输。在开发过程中,可以使用Android Studio提供的调试工具来调试应用程序,以确保应用程序的正确性和稳定性。 ### 回答2: 随着智能手表、智能眼镜、智能家居等智能设备的普及,无线通信技术也变得越来越重要。其中,蓝牙技术在无线通信领域中发挥着重要作用。蓝牙技术适用于开发不同场景的应用程序,例如远程控制、跟踪系统、移动支付、汽车和健康设备等。 Android Studio是一款专门用于Android应用程序开发IDE。它提供了许多功能,帮助开发者在蓝牙开发中更容易地进行连接和传输数据。 首先,我们需要在Android Studio中添加支持蓝牙的库。这可以通过在build.gradle文件中添加以下行来完成: implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support:design:28.0.0' implementation 'com.android.support:cardview-v7:28.0.0' implementation 'com.android.support:recyclerview-v7:28.0.0' implementation 'com.android.support:bluetooth:28.0.0' 接下来,我们需要在应用程序中声明需要使用蓝牙的权限: <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> 然后,在我们的Activity中初始化蓝牙适配器,并检查设备是否支持蓝牙。如果设备不支持蓝牙,则我们需要显示一条消息,否则我们可以进行下一步操作。初始化代码示例如下: private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { // 设备不支持蓝牙 Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show(); finish(); return; } 之后,我们需要搜索周围的蓝牙设备并显示它们的名称和地址。这可以通过使用BluetoothAdapter的startDiscovery方法实现。 mBluetoothAdapter.startDiscovery(); 在搜索结束时,系统会发出一个广播,我们需要注册一个广播接收器以处理这个广播并显示搜索结果。 private final BroadcastReceiver mReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { // 从intent中获取搜索结果 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // 将设备名称和地址显示在列表中 mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } }; 最后,我们可以创建一个蓝牙连接连接两个设备,并在他们之间传输数据。这可以通过使用BluetoothSocket和BluetoothDevice类实现。我们可以使用以下代码在Android设备蓝牙设备之间创建连接: BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(deviceAddress); BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid); // 启动连接 socket.connect(); 这些是在Android Studio开发蓝牙应用程序所需的基本步骤。然而,蓝牙开发还有许多其他方面需要考虑,例如蓝牙传输协议,数据加密和设备兼容性等等。综上所述,使用Android Studio可以轻松地开发蓝牙应用程序,这为我们实现智能设备之间的无缝连接和数据交换提供了方便。 ### 回答3: 在Android Studio开发蓝牙应用程序,需要了解蓝牙技术的基本知识,以便能够使用系统API和类库进行开发。 首先,需要在AndroidManifest.xml文件中声明蓝牙权限和蓝牙服务等信息。然后,在主活动或其他类中,需要引入相关的类库,例如BluetoothAdapter、BluetoothDevice、BluetoothSocket等,以便可以使用这些类库提供的API进行蓝牙功能开发。 在使用蓝牙功能的时候,需要注意以下几点: 1. 蓝牙必须先开启才能使用,需要使用BluetoothAdapter类的方法进行开启。 2. 扫描周围的设备需要使用startDiscovery()方法进行搜索,搜索完成后需要使用cancelDiscovery()方法停止搜索。 3. 连接一个蓝牙设备需要先通过BluetoothDevice类获取远程设备的地址和名称等信息,然后使用connectGatt()方法建立连接。 4. 在建立连接成功后可以通过BluetoothGatt类读取和写入数据或者订阅通知等操作。 5. 在蓝牙通信过程中如果发生错误需要及时处理,例如重新连接、关闭连接等操作。 最后,需要在程序中加入合适的UI界面,以方便用户可视化操作。同时,需要进行适当的测试和调试,保证程序的稳定运行和良好的用户体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值