Android——搜索传统蓝牙设备
一,主布局:
<?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 - 传统蓝牙通信聊天
Android -传统蓝牙通信聊天 技术:java+Android4.4+jdk1.8 运行环境:Android4.4.Android7.0 概述 Android 传统蓝牙的使用,包括开关蓝牙.搜索设 ...
- android搜索框列表布局,流程及主要步骤思维导图
android搜索框列表布局,流程及主要步骤思维导图 android搜索框列表布局,流程及主要步骤思维导图 activity_coin_search.xml----------<com.scwa ...
- Android -传统蓝牙通信聊天
概述 Android 传统蓝牙的使用,包括开关蓝牙.搜索设备.蓝牙连接.通信等. 详细 代码下载:http://www.demodashi.com/demo/10676.html 原文地址: Andr ...
- 【转】android蓝牙开发 蓝牙设备的查找和连接
1. 首先,要操作蓝牙,先要在AndroidManifest.xml里加入权限 // 管理蓝牙设备的权限 <uses-permissionandroid:name="android. ...
- Android搜索框效果
转载:http://blog.csdn.net/walker02/article/details/7917392 需求:项目中的有关搜索的地方,加上清空文字的功能,目的是为了增加用户体验,使用户删除文 ...
- Android中连接蓝牙设备时遇到createRfcommSocketToServiceRecord的UUID问题和BluetoothSocket的connect失败
[问题] 折腾: [记录]编写Android中的蓝牙模块驱动和底层HART设备 期间,参考: Bluetooth | Android Developers – ManagingAConnection ...
- Android搜索框以及内容提供器
先看结果: 相关的官方文档在这里:Creating a Search Interface Android官方提供了两种方式: 弹出一个Dialog,覆盖当前的Activity界面 在AppBar中扩展 ...
- Android搜索自动提示功能 AutocompleteTextView
1.配置main.xml中自动提示控件: <AutoCompleteTextView android:id="@+id/autotv_searchresult" androi ...
- Android搜索控件的基本使用方法
在Android中,搜索是一个非常核心的功能,我们可以通过它搜索到任意我们可以获得的信息.这些信息可以是存储在手机中的联系人.文件等信息,也可以是在网络上的资源. Android为了给用户提供良好的搜 ...
随机推荐
- 数字(int)转字符串和字符串转数字(int)
室友去面试,问了一个字符串转成数字的算法题,室友没搞出来,我心想,这个不是很简单的吗?于是动手在纸上画了画代码.画完后,总感觉哪里不对,最后一个个挖掘,才发现,尼玛,这到处都是坑啊---特此记录一下中 ...
- 从今天開始学习iOS开发(iOS 7版)--实现一款App之Foundation框架的使用
iOSFoundation框架 当你着手为你的应用编写代码的时候,你会发现有很多可供使用的Objective-C的框架类,当中尤其重要的就是基础框架类.它为平台全部的应用提供基础服务.基础框架类中包括 ...
- HDU 5723 最小生成树上的期望
题意:求最小生成树,和任意两个点之间距离的期望 官方题解: 最后求两遍点的积的时候,还是要判断父子关系. 注意 long long #include <bits/stdc++.h> usi ...
- VMWARE下CentOS7虚拟机网络配置
注:本文仅针对新装的虚拟机,#ip addr 获取不到ip信息,无法连接网络的情况提供一种参考解决方案. 1.左上角点击“编辑”->“虚拟网络编辑器”.新建一个NAT模式的网络. 2.配置虚拟机 ...
- 使用ToDateTime方法转换日期显示格式
实现效果: 知识运用: Convert类的ToDateTime方法:(将字符串转化为DateTime对象) public static DateTime ToDateTime(string value ...
- ASP.NET SignalR 与LayIM配合,轻松实现网站客服聊天室(六)之 好友申请、同意、拒绝
不知道距离上一篇多久没有写了,可能是因为忙(lan)的关系吧.废话不多说,今天要介绍的不算什么新知识,主要是逻辑上的一些东西.什么逻辑呢,加好友,发送好友申请,对方审批通过,拒绝.(很遗憾,对方审批通 ...
- Oracle连接问题
ORA-01034: ORACLE not availableORA-27101: shared memory realm does not exist sqlplus /nolog conn /as ...
- Spring Boot 配置文件详解:Properties和YAML
一.配置文件的生效顺序,会对值进行覆盖: 1. @TestPropertySource 注解 2. 命令行参数 3. Java系统属性(System.getProperties()) 4. 操作系统环 ...
- Android学习笔记_27_多媒体之视频刻录
一.配置文件: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android= ...
- JavaEE权限管理系统的搭建(六)--------使用拦截器实现菜单URL的跳转权限验证和页面的三级菜单权限按钮显示
本小结讲解,点击菜单进行页面跳转,看下图,点击管理员列表后会被认证拦截器首先拦截,验证用户是否登录,如果登录就放行,紧接着会被权限验证拦截器再次拦截,拦截的时候,会根据URL地址上找到对应的方法,然后 ...