Android Studio: 列出配对设备
创始人
2024-08-17 02:00:20
0

要在Android Studio中列出配对设备,可以使用以下代码示例:

  1. 在AndroidManifest.xml文件中添加以下权限:


  1. 在需要列出配对设备的Activity中,添加以下代码:
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    private BluetoothAdapter bluetoothAdapter;
    private ArrayAdapter pairedDevicesAdapter;
    private ArrayList pairedDevicesList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化BluetoothAdapter
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 初始化配对设备列表
        pairedDevicesList = new ArrayList<>();
        pairedDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, pairedDevicesList);

        ListView pairedDevicesListView = findViewById(R.id.paired_devices_listview);
        pairedDevicesListView.setAdapter(pairedDevicesAdapter);

        // 检查设备是否支持蓝牙
        if (bluetoothAdapter == null) {
            // 设备不支持蓝牙
            // 可以在这里做相应的处理
            return;
        }

        // 检查蓝牙是否已启用
        if (!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        } else {
            // 蓝牙已启用,列出配对设备
            listPairedDevices();
        }
    }

    private void listPairedDevices() {
        // 获取已配对设备列表
        Set pairedDevices = bluetoothAdapter.getBondedDevices();

        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                pairedDevicesList.add(device.getName() + "\n" + device.getAddress());
            }
        }

        pairedDevicesAdapter.notifyDataSetChanged();
    }
}

这段代码将在布局中的ListView中显示已配对设备的名称和地址。确保在layout文件中有一个ListView元素,并将其id设置为paired_devices_listview

注意:在使用蓝牙功能之前,请确保在AndroidManifest.xml文件中添加了相应的权限。

相关内容

热门资讯

固有有辅助"西元文山... 西元文山攻略是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以加我微信(...
从来有辅助"温州茶园... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
一向有辅助"wepo... wepoker辅助器免费下载是一款专注玩家量身打造的游戏记牌类型软件,在wepoker辅助器免费下载...
本来有辅助"poke... 本来有辅助"pokemmo手机辅助软件"开挂(透视)辅助软件(玩家教你有挂功能);无需打开直接搜索加...
往昔有开挂"微信卡五... 往昔有开挂"微信卡五星辅助"开挂(透视)辅助透视(透视教程有挂规律) 【无需打开直接搜索加薇1367...
固有有辅助"福建兄弟... 固有有辅助"福建兄弟十三水有没有挂"开挂(透视)辅助下载(分享教程有挂教学);无需打开直接搜索加薇1...
本然有开挂"打两圈兴... 本然有开挂"打两圈兴化辅助"开挂(透视)辅助安装(揭秘教程有挂分享)《详细加薇136704302咨询...
从前有辅助"wepo... wepoker插件程序激活码是一款专注玩家量身打造的游戏记牌类型软件,在wepoker插件程序激活码...
往昔有辅助"小程序可... 往昔有辅助"小程序可以开挂吗"开挂(透视)辅助插件(高科技教程有挂教学)您好:小程序可以开挂吗这款游...
先前有开挂"钱塘十三... 钱塘十三水透视 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理由: 1、...