You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中Wifi P2P列表无显示,Toast也不触发问题排查

排查Wifi P2P设备发现与列表/Toast显示问题

你遇到的问题是Wifi设备发现后列表不显示,无设备时Toast也不弹出?我帮你梳理下代码里的几个关键问题,这些应该就是导致异常的原因:

核心问题分析

  • UI操作不在主线程:onPeersAvailable回调是运行在Android的Binder线程(非主线程)中的,而Android明确要求所有UI操作必须在主线程执行。你直接在这里调用listView.setAdapter()和Toast的显示方法,系统会默默阻止这些操作(不会崩溃,但完全不生效)。
  • 上下文选择错误:使用getApplicationContext()给ArrayAdapter和Toast传上下文是不合适的。ArrayAdapter需要与ListView所在的Activity绑定,用Application Context可能导致布局渲染异常;Toast用Activity上下文会更可靠,尤其是在Activity处于活跃状态时。
  • 潜在的空指针风险:如果peers没有提前初始化为new ArrayList<WifiP2pDevice>(),当第一次回调且无设备时,peers.size()会直接抛出空指针异常,导致整个回调逻辑失败。
  • 适配器重复创建的冗余(可选优化):每次回调都新建ArrayAdapter没必要,复用现有适配器并更新数据会更高效。

修复后的代码示例

首先确保你已经在Activity里初始化了peers:

// 在Activity类中声明并初始化成员变量
private List<WifiP2pDevice> peers = new ArrayList<>();
private ArrayAdapter<String> deviceAdapter; // 复用适配器用

然后修改onPeersAvailable方法:

public void onPeersAvailable(WifiP2pDeviceList peerList) {
    // 将所有UI操作切换到主线程执行
    runOnUiThread(() -> {
        Collection<WifiP2pDevice> newPeerList = peerList.getDeviceList();
        
        // 更新设备列表数据
        if (!newPeerList.equals(peers)) {
            peers.clear();
            peers.addAll(newPeerList);

            // 准备列表显示的数据
            String[] deviceNames = new String[newPeerList.size()];
            WifiP2pDevice[] devices = new WifiP2pDevice[newPeerList.size()];
            int index = 0;
            for (WifiP2pDevice device : newPeerList) {
                deviceNames[index] = device.deviceName;
                devices[index] = device;
                index++;
            }

            // 复用适配器的写法(推荐)
            if (deviceAdapter == null) {
                deviceAdapter = new ArrayAdapter<>(YourActivityName.this,
                        android.R.layout.simple_list_item_1, deviceNames);
                listView.setAdapter(deviceAdapter);
            } else {
                deviceAdapter.clear();
                deviceAdapter.addAll(deviceNames);
                deviceAdapter.notifyDataSetChanged();
            }
        }

        // 无设备时显示Toast
        if (peers.isEmpty()) {
            Toast.makeText(YourActivityName.this, "No Device", Toast.LENGTH_SHORT).show();
        }
    });
}

关键注意事项

  • 把代码里的YourActivityName.this替换成你实际的Activity类名,确保使用Activity上下文。
  • 如果不需要复用适配器,也可以保留新建适配器的写法,但必须放在runOnUiThread内部。
  • 确认你的ListView已经通过findViewById正确初始化,避免空指针。

内容的提问来源于stack exchange,提问作者Jia Tang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:22:37