Android 蓝牙开发——获取已配对蓝牙并显示

68 篇文章 1 订阅

activity_blue_paired.xml布:里面有一个列表,用于显示所有已配对的设备

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center" 
    android:background="@color/white" 
    android:orientation="vertical">
    <TextView android:id="@+id/title" 
              style="@style/text_18_ffffff" 
              android:layout_width="fill_parent" 
              android:layout_height="60dp" 
              android:gravity="center" 
              android:background="#84b9ff" 
              android:text="已配对蓝牙列表" 
              android:visibility="visible" />
    <FrameLayout android:layout_width="match_parent" 
                 android:layout_height="120dp">
        <ListView android:id="@+id/lv_blue_paired" 
                  android:layout_width="match_parent" 
                  android:layout_height="wrap_content" 
                  android:divider="#e6e7e9" 
                  android:dividerHeight="1dp" 
                  android:headerDividersEnabled="true" 
                  android:footerDividersEnabled="true" 
                  android:scrollbars="none" 
                  android:cacheColorHint="#00000000" 
                  android:listSelector="#00000000" />
    </FrameLayout>
</LinearLayout>

PairedBluetoothDialogAdapter.java:listView的Adapter类,显示listView列表的每一项数据,其中有两个TextView控件,用来显示蓝牙名和蓝牙地址。还有一个BluetoothDevice对象,这个对象不是用来显示,是用来在列表点击时,返回蓝牙设备

public class PairedBluetoothDialogAdapter extends BaseAdapter { 
    public static final String TAG = "ListViewAdapter";
    private Context context;
    private List<HashMap> arrayList;
    public PairedBluetoothDialogAdapter(Context context, List<HashMap> arrayList){
        this.context = context;
        this.arrayList = arrayList;
    }
    @Override
    public int getCount() {
        return arrayList.size();
    }
    @Override
    public Object getItem(int position) {
        return arrayList.get(position);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder  holder = null;
        LayoutInflater  mInflater = LayoutInflater.from(context);
        if(convertView == null)
        {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.item_paired_bluetooth, null);
            holder.tvName = (TextView)convertView.findViewById(R.id.item_name);
            holder.tvAddress = (TextView)convertView.findViewById(R.id.item_address);
            convertView.setTag(holder);
        }else {
            Log.d(TAG, "not_null " + position);
            holder = (ViewHolder)convertView.getTag();
        }
        holder.device = (BluetoothDevice) ((HashMap)arrayList.get(position)).get("blue_device");
        holder.tvName.setText((String)((HashMap)arrayList.get(position)).get("blue_name"));
        holder.tvAddress.setText((String)((HashMap)arrayList.get(position)).get("blue_address"));
        return convertView;
    }
    static class ViewHolder
    {
        public BluetoothDevice device;//不是用来显示,用来在item点击时返回连接对象
        public TextView tvName;
        public TextView tvAddress;
    }
}

item_paired_bluetooth.xml:Adapter的布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"             
        android:id="@+id/list_item" 
        android:layout_width="match_parent" 
        android:orientation="horizontal" 
        android:layout_marginLeft="10dp" 
        android:layout_marginRight="10dp" 
        android:layout_height="48dp">
    <TextView android:id="@+id/item_name" 
              android:layout_width="wrap_content" 
              android:layout_height="48dp" 
              android:gravity="center_vertical" 
              android:textSize="18sp"/>
    <TextView android:id="@+id/item_address" 
              android:layout_width="match_parent" 
              android:layout_height="48dp" 
              android:gravity="center_vertical" 
              android:lines="1" 
              android:ellipsize="end" 
              android:layout_marginLeft="10dp" 
              android:textSize="16sp"/>
</LinearLayout>
 

java代码:显示蓝牙列表,并对点击事件做相应,可以在点击列表中获取到返回的蓝牙设备,并对其进行操作

public class BluePairedActivity extends Activity { 
    public static final String TAG ="Chunna==BlueActivity";
    private List<HashMap> blueList;
    private HashMap blueHashMap;
    private ListView glvPaired;
    private BluetoothAdapter adapter;
    private PairedBluetoothDialogAdapter pairedAdapter;
    public static BluetoothSocket socket;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blue_paired);
        initBlueTooth();
        glvPaired = (ListView)findViewById(R.id.lv_blue_paired);
        pairedAdapter = new PairedBluetoothDialogAdapter(this,blueList);
        pairedAdapter.notifyDataSetChanged();
        glvPaired.setAdapter(pairedAdapter);
        glvPaired.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice gDevice = (BluetoothDevice)(((HashMap)pairedAdapter.getItem(position)).get("blue_device"));
                Log.d(TAG, "想要连接的远程主机:" + gDevice);
                Log.d(TAG, "想要连接的远程主机:" + gDevice.toString());
                //然后就可以连接或者做操作啦
            }
        });
    }
    private void initBlueTooth() {
        adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter != null) {
            if (!adapter.isEnabled()) {
                adapter.enable();
                //sleep one second ,avoid do not discovery
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Set<BluetoothDevice> devices = adapter.getBondedDevices();
            blueList = new ArrayList<HashMap>();
            Log.d(TAG,"获取已经配对devices"+devices.size());
            for (BluetoothDevice bluetoothDevice : devices)
            {
                Log.d(TAG, "已经配对的蓝牙设备:");
                Log.d(TAG, bluetoothDevice.getName());
                Log.d(TAG, bluetoothDevice.getAddress());
                blueHashMap = new HashMap();
                blueHashMap.put("blue_device",bluetoothDevice);
                blueHashMap.put("blue_name",bluetoothDevice.getName());
                blueHashMap.put("blue_address",bluetoothDevice.getAddress());
                blueList.add(blueHashMap);
            }
    }else{
            ToastUtil.getShortToastByString(this,"本机没有蓝牙设备");
        }
    }
}

转载于:Android 蓝牙开发——获取已配对蓝牙并显示-蒲公英云

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是关于 Android 蓝牙开发的搜索、配对连接、通信大全。 ## 搜索蓝牙设备 要搜索蓝牙设备,需要先获取 BluetoothAdapter 实例,然后调用 startDiscovery() 方法开始搜索。搜索到设备后,将会触发 BroadcastReceiver 的 ACTION_FOUND 广播。 ```java BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); bluetoothAdapter.startDiscovery(); ``` ## 配对蓝牙设备配对蓝牙设备,需要先获取 BluetoothDevice 实例,然后调用 createBond() 方法开始配对配对成功后,将会触发 BroadcastReceiver 的 ACTION_BOND_STATE_CHANGED 广播。 ```java BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address); device.createBond(); ``` ## 连接蓝牙设备连接蓝牙设备,需要先获取 BluetoothDevice 实例,然后调用 connectGatt() 方法连接设备连接成功后,将会触发 BluetoothGattCallback 的 onConnectionStateChange() 方法。 ```java BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address); BluetoothGatt gatt = device.connectGatt(context, false, gattCallback); ``` ## 蓝牙通信 要进行蓝牙通信,需要先获取 BluetoothGattCharacteristic 实例,并设置通知属性。然后调用 writeCharacteristic() 方法进行数据发送。数据接收将会通过 BluetoothGattCallback 的 onCharacteristicChanged() 方法触发。 ```java BluetoothGattCharacteristic characteristic = gatt.getService(serviceUuid) .getCharacteristic(characteristicUuid); gatt.setCharacteristicNotification(characteristic, true); characteristic.setValue(data); gatt.writeCharacteristic(characteristic); ``` 以上就是 Android 蓝牙开发的搜索、配对连接、通信大全。希望能对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值