当前位置: 首页 > news >正文

Discoverydevice.java和activity_discoverydevice.xml

一、Discoverydevice.java

public class Discoverydevice extends AppCompatActivity {private DeviceAdapter   mAdapter2;private final List<DeviceClass> mbondDeviceList = new ArrayList<>();//搜索到的所有已绑定设备保存为列表private final List<DeviceClass> mfindDeviceList = new ArrayList<>();//搜索到的所有未绑定设备保存为列表private final BluetoothController mbluetoothController = new BluetoothController();private Toast mToast;private Button button;private BluetoothAdapter bluetoothAdapter;@SuppressLint("MissingPermission")@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_discoverydevice);bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();/*       View rootView = findViewById(android.R.id.content);开始扫描蓝牙设备View updatedView = findDevice(rootView);*/button = findViewById(R.id.button1);button.setOnClickListener(v -> {init_Filter();//初始化广播并打开Init_listView();//初始化设备列表findDevice(v);});ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);return insets;});}//初始化蓝牙权限private void Init_Bluetooth() {mbluetoothController.enableVisibily(this);//让其他蓝牙看得到我mbluetoothController.turnOnBlueTooth(this, 0);//打开蓝牙}//初始化列表,适配器的加载public void Init_listView() {mAdapter2 = new DeviceAdapter(Discoverydevice.this, R.layout.device_item, mfindDeviceList);ListView listView2 = findViewById(R.id.listview2);listView2.setAdapter(mAdapter2);mAdapter2.notifyDataSetChanged();listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {@SuppressLint("MissingPermission")@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {DeviceClass device = mfindDeviceList.get(position); // 获取点击的设备信息String deviceAddress = device.getbAdress();String deviceName= device.getbName();Intent resultIntent = new Intent( );resultIntent.putExtra("bluetoothName", deviceName);resultIntent.putExtra("bluetoothAddress", deviceAddress);// 设置结果代码为 RESULT_OK,表示连接成功setResult(Discoverydevice.RESULT_OK, resultIntent);// 关闭当前活动finish();showToast("连接中...");}});Init_Bluetooth();}//开启广播private void init_Filter() {IntentFilter filter = new IntentFilter();filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); //连接蓝牙,断开蓝牙//开始查找filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);//结束查找filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//查找设备 蓝牙发现新设备(未配对的设备)filter.addAction(BluetoothDevice.ACTION_FOUND);//设备扫描模式改变filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);//绑定状态 设备配对状态改变filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);//在系统弹出配对框之前(确认/输入配对码)filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);//最底层连接建立filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);//最底层连接断开filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED); //BluetoothAdapter连接状态filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); //BluetoothHeadset连接状态filter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED); //BluetoothA2dp连接状态registerReceiver(receiver, filter);}//广播内容private final BroadcastReceiver receiver = new BroadcastReceiver() {@SuppressLint("MissingPermission")@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//开始查找if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {change_Button_Text("搜索中...", "DISABLE");
//                showToast("搜索中..." );mfindDeviceList.clear();mAdapter2.notifyDataSetChanged(); //刷新列表适配器,将内容显示出来
//                }}//结束查找else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//                showToast("搜索设备..." );change_Button_Text("扫描设备", "ENABLE");}//查找设备else if (BluetoothDevice.ACTION_FOUND.equals(action)) {change_Button_Text("搜索中...", "DISABLE");
//                showToast("搜索中..." );if (device != null && device.getName() != null && !device.getName().isEmpty()) {change_Button_Text("搜索中...", "DISABLE");// showToast("搜索中...");//查找到一个设备且设备名不为空就添加到列表类中mfindDeviceList.add(new DeviceClass(device.getName(), device.getAddress()));mAdapter2.notifyDataSetChanged(); //刷新列表适配器,将内容显示出来show_bondDevice();}}//设备扫描模式改变else if (BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(action)) {int scanMode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, 0);if (scanMode == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {showToast("true");} else {showToast("false");}} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);if (remoteDevice == null) {return;}int status = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, 0);if (status == BluetoothDevice.BOND_BONDED) {showToast("已绑定---" + remoteDevice.getName());} else if (status == BluetoothDevice.BOND_BONDING) {showToast("正在绑定---" + remoteDevice.getName());} else if (status == BluetoothDevice.BOND_NONE) {showToast("未绑定---" + remoteDevice.getName());}}}};//点击开始查找蓝牙设备public void findDevice(View view) {mbluetoothController.findDevice();}// 判断是否连接  显示已连接设备信息private void show_bondDevice() {bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();BluetoothProfile.ServiceListener profileListener = new BluetoothProfile.ServiceListener() {@SuppressLint("MissingPermission")@Overridepublic void onServiceConnected(int profile, BluetoothProfile proxy) {if (profile == BluetoothProfile.A2DP) {List<BluetoothDevice> devices = proxy.getConnectedDevices();if (!devices.isEmpty()) {BluetoothDevice connectedDevice = devices.get(0);mbondDeviceList.clear();mbondDeviceList.add(new DeviceClass(connectedDevice.getName(), connectedDevice.getAddress()));//  button.setText(text);} else {// 展示已经配对的蓝牙设备show_bondDeviceList();}}}@Overridepublic void onServiceDisconnected(int profile) {// 展示已经配对的蓝牙设备show_bondDeviceList();}};bluetoothAdapter.getProfileProxy(Discoverydevice.this, profileListener, BluetoothProfile.A2DP);}// 未连接@SuppressLint("MissingPermission")private void show_bondDeviceList() {mbondDeviceList.clear();}//点击按键搜索后按键的变化private void change_Button_Text(String text, String state) {if ("ENABLE".equals(state)) {button.setEnabled(true);button.getBackground().setAlpha(255); //0~255 之间任意调整button.setTextColor(ContextCompat.getColor(this, R.color.black));} else {button.setEnabled(false);button.getBackground().setAlpha(150); //0~255 之间任意调整button.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));}button.setText(text);}//设置toast的标准格式private void showToast(String text) {if (mToast == null) {mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);mToast.show();} else {mToast.setText(text);mToast.show();}}@Overrideprotected void onDestroy() {super.onDestroy();unregisterReceiver(receiver);}}

二、 activity_discoverydevice.xml.

<?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:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#eeeeee"android:orientation="vertical"tools:context=".Discoverydevice"><Buttonandroid:id="@+id/button1"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="@drawable/button_style"android:text="扫描设备"android:textColor="#000000" /><TextViewandroid:id="@+id/textView1"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="50px"android:text="附近设备" /><ListViewandroid:id="@+id/listview2"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="20px"android:background="@drawable/listview_style1" /> 
</LinearLayout>

http://www.lryc.cn/news/338376.html

相关文章:

  • 华为OD机试 - 最多颜色的车辆(Java JS Python C C++)
  • 【无人机/平衡车/机器人】详解STM32+MPU6050姿态解算—卡尔曼滤波+四元数法+互补滤波——附3个算法源码
  • NzN的C++之路--构造函数与析构函数
  • 【算法刷题day24】Leetcode:216. 组合总和 III、17. 电话号码的字母组合
  • 一体化泵站的生产制造流程怎样
  • 【1】C++设计模式之【单例模式】
  • 软件设计模式之解释器模式
  • java Web课程管理系统用eclipse定制开发mysql数据库BS模式java编程jdbc
  • Electron 桌面端应用的使用 ---前端开发
  • 【SpringBoot:详解Bean装配】
  • 前端如何将接口返回的码值转成对应的中文展示呢?
  • 智慧公厕中的大数据、云计算和物联网技术引领未来公厕管理革命
  • Excel与项目管理软件比较?哪个是项目组合管理的最佳选择?
  • 过程控制风格的软件架构设计概念及其实际应用
  • WPF 编辑器模式中隐藏/显示该元素
  • 分布式事务 - 个人笔记 @by_TWJ
  • 解决前端笔记本电脑屏幕显示缩放比例125%、150%对页面大小的影响问题--数据可视化大屏
  • 【PG-1】PostgreSQL体系结构概述
  • jq命令简易教程——Linux中处理JSON数据的利器
  • 前端开发攻略---Vue实现防篡改水印的效果。删除元素无效!更改元素属性无效!支持图片、元素、视频等等。
  • 在Go语言中复制sync类型
  • Golang | Leetcode Golang题解之第25题K个一组翻转链表
  • 【初学】前后端flask+vue组合GET案例
  • 计算机科学与技术CS考研408资料
  • ACID模型是什么
  • 【Linux】基础IO----理解缓冲区
  • java学习之路-继承
  • Linux系统——Elasticsearch企业级日志分析系统
  • 多协议接入视频汇聚EasyCVR平台vs.RTSP安防视频EasyNVR平台:设备分组的区别
  • Spring Security Oauth2 之 理解OAuth 2.0授权流程