首页 > 其他分享 >Android BluetoothAdapter 使用(二)

Android BluetoothAdapter 使用(二)

时间:2023-12-26 20:36:45浏览次数:26  
标签:BluetoothDevice BluetoothAdapter convertView context 使用 import Android public an

Android BluetoothAdapter 使用(二)

本篇文章主要讲下蓝牙设备的配对.

1: 蓝牙设备列表展示

下 面是蓝牙设备adapter的代码:

package com.test.bluetooth;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.List;

/**
 * @Author: zh
 * @Time: 23-12-12.
 * @Email: 
 * @Describe:
 */
public class DeviceAdapter extends BaseAdapter {
    private Context context;
    private List<BluetoothDevice> list;

    public DeviceAdapter(Context context, List<BluetoothDevice> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_device, parent, false);
        }
        BluetoothDevice bluetoothDevice = list.get(position);
        TextView name = convertView.findViewById(R.id.item_name);
        TextView address = convertView.findViewById(R.id.item_address);
        name.setText(bluetoothDevice.getName());
        address.setText(bluetoothDevice.getAddress());
        View viewById = convertView.findViewById(R.id.item_btn);
        viewById.setOnClickListener(v -> {
            if (deviceConnect != null)
                deviceConnect.doAction(bluetoothDevice);
        });
        return convertView;
    }

    DeviceConnect deviceConnect;

    public void setDeviceConnect(DeviceConnect deviceConnect) {
        this.deviceConnect = deviceConnect;
    }

    public interface DeviceConnect {
        void doAction(BluetoothDevice bluetoothDevice);
    }


}

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="wrap_content"
    android:orientation="vertical"
    >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="15dp"
        android:id="@+id/item_name"
        android:text="xxxxx"
        android:textSize="20sp"
        />
     <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:id="@+id/item_address"
         android:layout_marginTop="5dp"
         android:layout_marginLeft="15dp"
         android:textSize="16sp"
         />
     <Button
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:textSize="16sp"
         android:text="配对"
         android:layout_marginTop="5dp"
         android:layout_marginLeft="15dp"
         android:id="@+id/item_btn"
         />
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="15dp"
        android:background="#333"
        />
</LinearLayout>

另外由于嵌套使用listview. 这里简单自定义了listview,重新计算了高度.

package com.test.bluetooth;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;

public class MyListView extends ListView {

    public MyListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int mExpandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, mExpandSpec);
    }
}

扫描蓝牙设备列表的代码,可以看下我的上篇文章,这里简单写下:

private final BroadcastReceiver receiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Discovery has found a device. Get the BluetoothDevice
            // object and its info from the Intent.
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String deviceName = device.getName();
            String deviceHardwareAddress = device.getAddress(); // MAC address
            if (!TextUtils.isEmpty(deviceName)){
                listFind.add(device);
                findAdapter.notifyDataSetChanged();
            }
            Log.d(TAG, "onReceive: deviceName:" + deviceName + "; deviceHardwareAddress:" + deviceHardwareAddress);
        }
    }
};
findAdapter.setDeviceConnect(new DeviceAdapter.DeviceConnect() {
    @Override
    public void doAction(BluetoothDevice bluetoothDevice) {
        bindDevice(bluetoothDevice.getAddress());
    }
});

配对设备的代码如下:

private void bindDevice(String address) {
    BluetoothDevice remoteDevice = bluetoothAdapter.getRemoteDevice(address);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        remoteDevice.createBond();
    }
}

点击效果如下:

image-20231212210245353

标签:BluetoothDevice,BluetoothAdapter,convertView,context,使用,import,Android,public,an
From: https://www.cnblogs.com/zhjing/p/17929291.html

相关文章

  • API 参考与帮助内容:一站式开发与使用者支援
    API文档API文档是旨在了解API详细信息的综合指南。通常,它们包括端点、请求示例、响应类别和示例以及错误代码等信息。API文档可帮助开发人员了解API端点的具体细节,并了解如何将API成功集成到他们的软件中。文档生成工具API文档生成工具是直接从源代码创建API文档的......
  • python tkinter 使用(七)
    pythontkinter使用(七)本篇文章主要讲下tkinter中的message控件.Message控件可以用于在窗口中显示一段文本消息.以下是个简单的例子:#!/usr/bin/python3#-*-coding:UTF-8-*-"""@Author:zh@Time2023/11/24上午11:38.@Email:@Describe:"""fromtkinte......
  • python tkinter使用(九)
    pythontkinter使用(九)本文主要讲下scrolledText中图片的插入,以及常见的错误.使用Image.open来打开图片使用ImageTk.PhotoImage()方法将图片转换为tkinter中的图片对象使用insert()方法插入图片ImageTk直接引入后,会遇到如下错误:Traceback(mostrecentcalllast):......
  • python tkinter 使用(二)
    pythontkinter使用(二)本篇文章着重讲下tkinter中messagebox的使用。1:提示框defshowinfo(event):messagebox.showinfo("这是个提示框","thisismessagecontent")2:错误提示框defshowerror(event):messagebox.showerror("这是个错误提示框","thisismessa......
  • python tkinter 使用(十)
    pythontkinter使用(十)#!/usr/bin/python3#-*-coding:UTF-8-*-"""@Author:zh@Time2023/11/27下午3:36.@Email:@Describe:"""importtkinterfromtkinterimport*master=Tk()master.title("菜单")master.ge......
  • python tkinter 使用(三)
    pythontkinter使用(三)本篇文章主要讲下tkinter下的filedialog的使用.1:askopenfilename首先使用tkinter中fiedialog来实现一个简单的文件选择器.这里使用askopenfilename()来启动文件选择器,选择成功后打印下所选文件的名称.#!/usr/bin/python3#-*-coding:UTF-8-*-......
  • python tkinter使用(五)
    pythontkinter使用(五)本篇文章讲述tkinter中treeview的使用Treeview是一个多列列表框,可以显示层次数据。#!/usr/bin/python3#-*-coding:UTF-8-*-"""@Author:zh@Time2023/11/23下午8:28.@Email:@Describe:treeview使用"""importtkinterastkfrom......
  • python tkinter使用(四)
    pythontkinter使用(四)本篇文章主要讲下tkinter的文本框相关.tkinter中用Entry来实现输入框,类似于android中的edittext.具体的用法如下:1:空白输入框如下:name=tk.Entry(window)name.pack()2:设置输入框的默认文案name=tk.Entry(window)name.pack()name.inser......
  • python tkinter使用(十一)
    pythontkinter使用(十一)本篇文章主要讲下tkinter窗口的一些属性,以及实现无法关闭的窗口中遇到的一些问题.#!/usr/bin/python3#-*-coding:UTF-8-*-"""@Author:zh@Time2023/11/28下午13:23.@Email:@Describe:"""fromtkinterimport*importtkinteras......
  • Android Notification 以及 通知铃音使用
    AndroidNotification以及通知铃音使用上一篇文章讲了手机震动的使用.本篇继续讲解铃音的使用,并且在讲下通知消息的使用.1:通知消息的使用代码如下:publicstaticvoidnotice(Contextcontext){try{NotificationCompat.Builderbuilder=ne......