Android——搜索传统蓝牙设备

简介:  一,主布局:  二,列表Item 三,蓝牙权限配置 四,activity上代码package com.


 一,主布局:


 

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


    <ListView
        android:layout_weight="5"
        android:id="@+id/test_list_bluetooth"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ListView>



    <LinearLayout
        android:layout_weight="0.2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
           android:layout_gravity="left"
            android:layout_margin="10dp"
            android:id="@+id/scan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="扫描蓝牙设备" />

        <Button
            android:id="@+id/btn_scan_ble"
            android:text="扫描BLE设备"
            android:layout_gravity="right"
            android:layout_margin="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

        <Button
        android:id="@+id/btn_stopscan"
        android:text="停止扫描"
        android:layout_gravity="right"
        android:layout_margin="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    </LinearLayout>

</LinearLayout>



二,列表Item

<?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">

    <TextView
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginBottom="20dp"
        android:layout_weight="1"
        android:hint="蓝牙名称"
        android:id="@+id/test_bluetooth_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginBottom="20dp"
        android:layout_weight="1"
        android:hint="蓝牙地址"
        android:id="@+id/test_bluetooth_addr"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:textColor="@color/txt_blue"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginBottom="20dp"
        android:layout_weight="1"
        android:hint="绑定状态"
        android:id="@+id/test_device_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


三,蓝牙权限配置


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


四,activity上代码


package com.woasis.batteries.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.woasis.batteries.R;
import com.woasis.batteries.lib.bluttoth.BluetoothData;
import com.woasis.batteries.lib.bluttoth.BluetoothService;

import java.io.IOError;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ListView mListView;//列表对象
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    List<Map<String,String>> deviceList;//列表数据源
    SimpleAdapter listItemAdapter;
    BluetoothAdapter bluetoothAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.scan).setOnClickListener(this);
        findViewById(R.id.btn_stopscan).setOnClickListener(this);
        findViewById(R.id.btn_scan_ble).setOnClickListener(this);
        mListView=(ListView)findViewById(R.id.test_list_bluetooth);
        registerReceiver(mReceiver, filter);
       // bluetoothService = BluetoothService.getInstance(this, BluetoothService.BluetoothType.b4);
       // bluetoothService.setmBluetoothData(new BluetoothData("INVENT-7CEC7933","123"));
    }

    private Handler handler=new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:/*停止扫描*/
                    listItemAdapter.notifyDataSetChanged();
                    Log.i("handler--0---收到消息:",deviceList.toString());
                    break;
                case 1:/*更新listview数据源*/
                    Bundle b =msg.getData();
                    String deviceName=b.getString("deviceName");
                    String deviceAddress=b.getString("deviceAddress");
                    Map map=new HashMap();
                    map.put("deviceName",deviceName);
                    map.put("deviceAddress",deviceAddress);
                    map.put("bluetooth_status","未配对");
                    boolean isAdd=false;
                    for(Map m :deviceList){
                        if(m.get("deviceAddress")!=map.get("deviceAddress")){
                            isAdd=true;
                        }
                    }
                    if(isAdd) {
                        deviceList.add(map);
                    }
                    listItemAdapter.notifyDataSetChanged();
                    Log.i("handler--1---收到消息:",map.toString());
                    break;
                default:
                    break;
            }
        }
    };
    BluetoothService bluetoothService;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.scan:
                // bluetoothService.startBluetooth();
                //1,初始化蓝牙适配器
                final BluetoothManager bluetoothManager=(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
                 bluetoothAdapter= bluetoothManager.getAdapter();
                //2,开启蓝牙
                if(bluetoothAdapter==null || !bluetoothAdapter.isEnabled()){
                    Intent enableBtIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent,1);
                }
                //3,扫描附近的设备
                deviceList=new ArrayList<>();

                if(bluetoothAdapter.isDiscovering()){
                    bluetoothAdapter.cancelDiscovery();
                }else{
                    //每次扫描之前都先判断一下是否存在已久配对的设备
                    Set<BluetoothDevice> paireDevices=bluetoothAdapter.getBondedDevices();
                    if(paireDevices.size()>0){
                        for(BluetoothDevice device :paireDevices){
                            Map map=new HashMap();
                            map.put("deviceName",device.getName());
                            map.put("deviceAddress",device.getAddress());
                            map.put("bluetooth_status","已配对");

                            deviceList.add(map);


                        }
                        Log.i("之前已经绑定过的设备:",deviceList.toString());
                    }
                    bluetoothAdapter.startDiscovery();//开始搜索
                }

                /*数据绑定listView*/
                if(deviceList!=null && deviceList.size()>0){
                    listItemAdapter=new SimpleAdapter(getBaseContext(),/*指明了SimpleAdapter关联的View的运行环境,也就是当前的Activity*/
                            deviceList,/*由Map组成的List,在List中的每条目对应ListView的一行,每一个Map中包含的就是所有在from参数中指定的key*/
                            R.layout.test_item_bluetooth_list,/*定义列表项的布局文件的资源ID,该资源文件至少应该包含在to参数中定义的ID*/
                            new String[]{"deviceName","deviceAddress","bluetooth_status"},/*将被添加到Map映射上的Key*/
                            new int[] {R.id.test_bluetooth_name,R.id.test_bluetooth_addr,R.id.test_device_status}/*将绑定数据的视图的Id跟from参数对应,这些被绑定的视图元素应该全是TextView*/
                    );
                    //设置适配器
                    mListView.setAdapter(listItemAdapter);
                }

                break;
            case R.id.btn_stopscan:
                Log.i("停止蓝牙扫描-------",String.valueOf(System.currentTimeMillis()));
                bluetoothAdapter.cancelDiscovery();//停止扫描
                break;
            case R.id.btn_scan_ble:/*扫描BLE设备*/
                break;
            default:
                break;
        }
    }


    /*监听扫描过程中的变化*/
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action))
            {
                // Get the BluetoothDevice object from the Intent
                // 通过EXTRA_DEVICE附加域来得到一个BluetoothDevice设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                // If it's already paired, skip it, because it's been listed already
                // 如果这个设备是不曾配对过的,添加到list列表
                if (device.getBondState() != BluetoothDevice.BOND_BONDED)
                {
                    Message msg=new Message();
                    msg.what=1;
                    Bundle bundle=new Bundle();
                    bundle.putString("deviceName",device.getName());
                    bundle.putString("deviceAddress",device.getAddress());
                    msg.setData(bundle);
                    handler.sendMessage(msg);

                    Map map=new HashMap();
                    map.put("deviceName",device.getName());
                    map.put("deviceAddress",device.getAddress());
                    Log.i("扫描到的新设备:",map.toString());
                    Log.i("加入新设备之后,扫描到的总设备:",deviceList.toString());
                }
                // When discovery is finished, change the Activity title
            }
            else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
            {
                Log.i("扫描结束------扫描到的总设备:",deviceList.toString());
               handler.obtainMessage(0).sendToTarget();
            }
        }
    };



}







目录
相关文章
|
数据库 Android开发
Android使用EditText+Listview实现搜索效果(使用room模糊查询)
本文介绍如何在Android中使用EditText与ListView实现搜索功能,并结合Room数据库完成模糊查询。主要内容包括:Room的模糊查询语句(使用`||`代替`+`号)、布局美化(如去除ListView分割线和EditText下划线)、EditText回车事件监听,以及查询逻辑代码示例。此外,还提供了相关扩展文章链接,帮助读者深入了解ListView优化、动态搜索及Room基础操作。
893 65
|
存储 Android开发
如何查看Flutter应用在Android设备上已被撤销的权限?
如何查看Flutter应用在Android设备上已被撤销的权限?
930 64
|
存储 Android开发 数据安全/隐私保护
如何在Android设备上撤销Flutter应用程序的所有权限?
如何在Android设备上撤销Flutter应用程序的所有权限?
1219 64
|
缓存 Android开发 开发者
Flutter环境配置完成后,如何在Android设备上运行Flutter应用程序?
Flutter环境配置完成后,如何在Android设备上运行Flutter应用程序?
3133 62
|
开发工具 Android开发 开发者
在Android设备上运行Flutter应用程序时,如果遇到设备未授权的问题该如何解决?
在Android设备上运行Flutter应用程序时,如果遇到设备未授权的问题该如何解决?
1297 61
|
Android开发 开发者
Android动态搜索的简单实现
本文介绍了在Android中实现动态搜索功能的方法,重点讲解了通过`SearchView`与`ListView`结合的方式。文章首先简要提及了`addTextChangedListener`的使用场景,随后详细说明了`SearchView`的相关方法,如`setIconified()`、`setOnQueryTextListener()`等,并通过一个示例展示了如何根据用户输入动态过滤`ListView`中的数据。案例中使用了一个字符串数组作为数据源,通过监听输入变化实现搜索功能。最后提供了完整的源码和布局文件,便于开发者参考和实践。
363 3
|
监控 Shell Linux
Android调试终极指南:ADB安装+多设备连接+ANR日志抓取全流程解析,覆盖环境变量配置/多设备调试/ANR日志分析全流程,附Win/Mac/Linux三平台解决方案
ADB(Android Debug Bridge)是安卓开发中的重要工具,用于连接电脑与安卓设备,实现文件传输、应用管理、日志抓取等功能。本文介绍了 ADB 的基本概念、安装配置及常用命令。包括:1) 基本命令如 `adb version` 和 `adb devices`;2) 权限操作如 `adb root` 和 `adb shell`;3) APK 操作如安装、卸载应用;4) 文件传输如 `adb push` 和 `adb pull`;5) 日志记录如 `adb logcat`;6) 系统信息获取如屏幕截图和录屏。通过这些功能,用户可高效调试和管理安卓设备。
11482 2
|
Android开发
Android 配置蓝牙遥控器键值
本文详细介绍了Android系统中配置蓝牙遥控器键值的步骤,包括查看设备号、配置键位映射文件(kl文件)、部署kl文件以及调试过程,确保蓝牙遥控器的按键能正确映射到Android系统对应的按键功能。
4187 1
|
Android开发
基于Amlogic 安卓9.0, 驱动简说(四):Platform平台驱动,驱动与设备的分离
本文介绍了如何在基于Amlogic T972的Android 9.0系统上使用Platform平台驱动框架和设备树(DTS),实现设备与驱动的分离,并通过静态枚举在设备树中描述设备,自动触发驱动程序的加载和设备创建。
647 0
基于Amlogic 安卓9.0, 驱动简说(四):Platform平台驱动,驱动与设备的分离
|
传感器 Android开发 芯片
不写一行代码(三):实现安卓基于i2c bus的Slaver设备驱动
本文是系列文章的第三篇,展示了如何在Android系统中利用现有的i2c bus驱动,通过编写设备树节点和应用层的控制代码,实现对基于i2c bus的Slaver设备(如六轴陀螺仪模块QMI8658C)的控制,而无需编写设备驱动代码。
780 0
不写一行代码(三):实现安卓基于i2c bus的Slaver设备驱动

热门文章

最新文章