蓝牙打开和搜索并显示在列表

本文详细介绍了在Android 6.0及以上版本中实现蓝牙搜索功能的过程,特别关注了权限管理和listView更新的问题。作者分享了如何正确处理蓝牙权限,确保startDiscovery方法能够正常工作,并解决了listView重复添加的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开始第一天,着手这个项目的学习。

首先写一个简单的布局文件,包含三个按钮,一个listView列表显示搜索到的蓝牙

样式如图:

布局文件如下:

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

    <Button
        android:id="@+id/turn_on"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="turn on"
        android:textAllCaps="false"/>
    <Button
        android:id="@+id/turn_off"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="turn off"
        android:textAllCaps="false"/>
    <Button
        android:id="@+id/search_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="search"
        android:textAllCaps="false"/>

    <ListView
        android:id="@+id/search_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></ListView>
    
</LinearLayout>

我将两个功能的代码暂写在MainActivity中,如下:

package com.example.hitmi.bluetoothtest;

import android.Manifest;
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.
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值