Android官方开发文档Training系列课程中文版:连接无线设备之通过WIFI创建P2P连接

本文主要是介绍Android官方开发文档Training系列课程中文版:连接无线设备之通过WIFI创建P2P连接,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

原文地址:http://android.xsoftlab.net/training/connect-devices-wirelessly/wifi-direct.html#permissions

Wi-Fi peer-to-peer (P2P) APIs可以使程序与附近的设备进行直接通讯,Android的Wi-Fi P2P框架由Wi-Fi Direct™提供技术支持。WI-FI P2P技术可以使程序快速的检索附近的设备并与之建立连接。其覆盖范围超过蓝牙的覆盖范围。

这节课会学习如何通过WI-FI P2P技术搜索附近的设备并与之建立连接。

设置应用权限

如果要使用WI-FI P2P技术,需要在程序的清单文件中添加CHANGE\_WIFI\_STATE, ACCESS\_WIFI\_STATE, INTERNET三项权限。Wi-Fi P2P并不需要互联网连接,但是它需要使用标准的Java Socket通讯技术,所以需要使用INTERNET权限:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.android.nsdchat"...<uses-permissionandroid:required="true"android:name="android.permission.ACCESS_WIFI_STATE"/><uses-permission
        android:required="true"android:name="android.permission.CHANGE_WIFI_STATE"/><uses-permission
        android:required="true"android:name="android.permission.INTERNET"/>...

设置广播接收器及P2P管理员

使用WI-FI P2P技术,需要监听广播意图,广播意图会通知程序某些事件的发生。所以在程序中需要添加IntentFilter,并设置其监听以下行为:

WIFI\_P2P\_STATE\_CHANGED\_ACTION

监听Wi-Fi P2P是否可用

WIFI\_P2P\_PEERS\_CHANGED\_ACTION

监听WI-FI P2P列表的变化

WIFI\_P2P\_CONNECTION\_CHANGED\_ACTION

监听Wi-Fi P2P的连接状态

WIFI\_P2P\_THIS\_DEVICE\_CHANGED\_ACTION

监听设备的配置变化
private final IntentFilter intentFilter = new IntentFilter();
...
@Override
public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);//  Indicates a change in the Wi-Fi P2P status.intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);// Indicates a change in the list of available peers.intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);// Indicates the state of Wi-Fi P2P connectivity has changed.intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);// Indicates this device's details have changed.intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);...
}

在onCreate()方法的末尾,需要获取WifiP2pManager的实例,然后调用它的initialize()方法。这个方法会返回一个WifiP2pManager.Channel的对象,它用于使程序应用层与Wi-Fi P2P框架建立连接。

@Override
Channel mChannel;
public void onCreate(Bundle savedInstanceState) {....mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);mChannel = mManager.initialize(this, getMainLooper(), null);
}

接下来创建一个新的BroadcastReceiver类,它用于监听系统的Wi-Fi P2P的状态变化,在onReceive()方法中,需要添加一些基本的判断条件来处理每种P2P的状态并处理:

    @Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {// Determine if Wifi P2P mode is enabled or not, alert// the Activity.int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {activity.setIsWifiP2pEnabled(true);} else {activity.setIsWifiP2pEnabled(false);}} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {// The peer list has changed!  We should probably do something about// that.} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {// Connection state changed!  We should probably do something about// that.} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {DeviceListFragment fragment = (DeviceListFragment) activity.getFragmentManager().findFragmentById(R.id.frag_list);fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));}}

最后,将广播接收器与意图过滤器添加到上下文中,并需要在Activity暂停的时候注销这个广播接收器。放置这些代码的最佳位置就是onResume()方法与onPause()方法。

    /** register the BroadcastReceiver with the intent values to be matched */@Overridepublic void onResume() {super.onResume();receiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);registerReceiver(receiver, intentFilter);}@Overridepublic void onPause() {super.onPause();unregisterReceiver(receiver);}

初始化端点搜索

如果开始要使用Wi-Fi P2P来搜索附近的设备,需要调用discoverPeers()方法。这个方法要求传入以下参数:

  • 在初始化P2P管理员时获得的WifiP2pManager.Channel对象。
  • WifiP2pManager.ActionListener的实现,它用于监听搜索的成功与否。
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {@Overridepublic void onSuccess() {// Code for when the discovery initiation is successful goes here.// No services have actually been discovered yet, so this method// can often be left blank.  Code for peer discovery goes in the// onReceive method, detailed below.}@Overridepublic void onFailure(int reasonCode) {// Code for when the discovery initiation fails goes here.// Alert the user that something went wrong.}
});

要记住,这里只是初始化了端点搜索。discoverPeers()方法启动搜索进程后会立即返回。如果端点搜索进程成功初始化,那么系统会自动调用初始化时设置的回调方法。另外,端点搜索功能会一直保持在活动状态,直到连接初始化完成或者P2P组建立连接。

获取端点列表

接下来需要获得并处理端点列表。首先需要实现WifiP2pManager.PeerListListener接口,它提供了WI-FI P2P所搜索到的端点信息。下面的代码演示了这个过程:

    private List peers = new ArrayList();...private PeerListListener peerListListener = new PeerListListener() {@Overridepublic void onPeersAvailable(WifiP2pDeviceList peerList) {// Out with the old, in with the new.peers.clear();peers.addAll(peerList.getDeviceList());// If an AdapterView is backed by this data, notify it// of the change.  For instance, if you have a ListView of available// peers, trigger an update.((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged();if (peers.size() == 0) {Log.d(WiFiDirectActivity.TAG, "No devices found");return;}}}

现在需要修改广播接收器的onReceive()方法,在收到WIFI\_P2P\_STATE\_CHANGED\_ACTION行为时调用requestPeers()方法。在这之前需要将监听器的实例传入到广播接收器中,常规的方式是在广播接收器的构造方法中将这个监听器传进来。、

public void onReceive(Context context, Intent intent) {...else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {// Request available peers from the wifi p2p manager. This is an// asynchronous call and the calling activity is notified with a// callback on PeerListListener.onPeersAvailable()if (mManager != null) {mManager.requestPeers(mChannel, peerListListener);}Log.d(WiFiDirectActivity.TAG, "P2P peers changed");}...
}

现在,WIFI\_P2P\_STATE\_CHANGED\_ACTION的行为将会触发端点列表的更新。

连接到端点

为了可以连接到端点,需要创建一个新的WifiP2pConfig对象,然后将WifiP2pDevice中的数据拷贝进这个对象中。WifiP2pDevice代表的将要连接的设备。然后调用connect()方法。

    @Overridepublic void connect() {// Picking the first device found on the network.WifiP2pDevice device = peers.get(0);WifiP2pConfig config = new WifiP2pConfig();config.deviceAddress = device.deviceAddress;config.wps.setup = WpsInfo.PBC;mManager.connect(mChannel, config, new ActionListener() {@Overridepublic void onSuccess() {// WiFiDirectBroadcastReceiver will notify us. Ignore for now.}@Overridepublic void onFailure(int reason) {Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",Toast.LENGTH_SHORT).show();}});}

上述代码中的WifiP2pManager.ActionListener接口只有在初始化成功或者失败的情况下才会调用。如果要监听连接状态的变化,需要实现WifiP2pManager.ConnectionInfoListener接口,它的方法onConnectionInfoAvailable()会在连接状态发生变化的时候回调。在多台设备连接一台设备的情况下(比如多人互动的游戏或者聊天类的APP),其中一台设备会被指定为”group owner”。

    @Overridepublic void onConnectionInfoAvailable(final WifiP2pInfo info) {// InetAddress from WifiP2pInfo struct.InetAddress groupOwnerAddress = info.groupOwnerAddress.getHostAddress());// After the group negotiation, we can determine the group owner.if (info.groupFormed && info.isGroupOwner) {// Do whatever tasks are specific to the group owner.// One common case is creating a server thread and accepting// incoming connections.} else if (info.groupFormed) {// The other device acts as the client. In this case,// you'll want to create a client thread that connects to the group// owner.}}

现在回到广播接收器的onReceive()方法,修改监听WIFI\_P2P\_CONNECTION\_CHANGED\_ACTION的部分,当这个意图接收到时,调用requestConnectionInfo()方法。这是一个异步方法,所以结果会通过参数:连接信息监听器回调回来。

        ...} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {if (mManager == null) {return;}NetworkInfo networkInfo = (NetworkInfo) intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);if (networkInfo.isConnected()) {// We are connected with the other device, request connection// info to find group owner IPmManager.requestConnectionInfo(mChannel, connectionListener);}...

这篇关于Android官方开发文档Training系列课程中文版:连接无线设备之通过WIFI创建P2P连接的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1012984

相关文章

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

使用Python开发一个现代化屏幕取色器

《使用Python开发一个现代化屏幕取色器》在UI设计、网页开发等场景中,颜色拾取是高频需求,:本文主要介绍如何使用Python开发一个现代化屏幕取色器,有需要的小伙伴可以参考一下... 目录一、项目概述二、核心功能解析2.1 实时颜色追踪2.2 智能颜色显示三、效果展示四、实现步骤详解4.1 环境配置4.

Java中实现线程的创建和启动的方法

《Java中实现线程的创建和启动的方法》在Java中,实现线程的创建和启动是两个不同但紧密相关的概念,理解为什么要启动线程(调用start()方法)而非直接调用run()方法,是掌握多线程编程的关键,... 目录1. 线程的生命周期2. start() vs run() 的本质区别3. 为什么必须通过 st

全屋WiFi 7无死角! 华硕 RP-BE58无线信号放大器体验测评

《全屋WiFi7无死角!华硕RP-BE58无线信号放大器体验测评》家里网络总是有很多死角没有网,我决定入手一台支持Mesh组网的WiFi7路由系统以彻底解决网络覆盖问题,最终选择了一款功能非常... 自2023年WiFi 7技术标准(IEEE 802.11be)正式落地以来,这项第七代无线网络技术就以超高速

Python使用smtplib库开发一个邮件自动发送工具

《Python使用smtplib库开发一个邮件自动发送工具》在现代软件开发中,自动化邮件发送是一个非常实用的功能,无论是系统通知、营销邮件、还是日常工作报告,Python的smtplib库都能帮助我们... 目录代码实现与知识点解析1. 导入必要的库2. 配置邮件服务器参数3. 创建邮件发送类4. 实现邮件

C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式

《C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式》Markdown凭借简洁的语法、优良的可读性,以及对版本控制系统的高度兼容性,逐渐成为最受欢迎的文档格式... 目录为什么要将文档转换为 Markdown 格式使用工具将 Word 文档转换为 Markdown(.

详解如何使用Python构建从数据到文档的自动化工作流

《详解如何使用Python构建从数据到文档的自动化工作流》这篇文章将通过真实工作场景拆解,为大家展示如何用Python构建自动化工作流,让工具代替人力完成这些数字苦力活,感兴趣的小伙伴可以跟随小编一起... 目录一、Excel处理:从数据搬运工到智能分析师二、PDF处理:文档工厂的智能生产线三、邮件自动化:

Python实现自动化Word文档样式复制与内容生成

《Python实现自动化Word文档样式复制与内容生成》在办公自动化领域,高效处理Word文档的样式和内容复制是一个常见需求,本文将展示如何利用Python的python-docx库实现... 目录一、为什么需要自动化 Word 文档处理二、核心功能实现:样式与表格的深度复制1. 表格复制(含样式与内容)2

java连接opcua的常见问题及解决方法

《java连接opcua的常见问题及解决方法》本文将使用EclipseMilo作为示例库,演示如何在Java中使用匿名、用户名密码以及证书加密三种方式连接到OPCUA服务器,若需要使用其他SDK,原理... 目录一、前言二、准备工作三、匿名方式连接3.1 匿名方式简介3.2 示例代码四、用户名密码方式连接4