注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好。

原文链接:http://developer.android.com/training/connect-devices-wirelessly/nsd-wifi-direct.html


在这系列课程的第一节课中(博客链接:http://www.cnblogs.com/jdneo/p/3579936.html),向你展示了如何发现连接到本地网络上的服务。然而,使用Wi-Fi Peer-to-Peer(P2P)服务搜索会允许你直接发现附近设备的服务,而不需要连接到网络中。你也可以对外广播目前正在你的设备上运行的服务。这些功能帮助你和其它应用进行通信,甚至是当无法获取本地网络或者热点的情况下。

虽然此API所要达到的目的,和之前课程中所说的NSD API非常类似,但是实现它们的代码却是不同的。这节课将向你展示如何使用Wi-Fi P2P从其他设备发现可获得的服务。这节课假设你已经对Wi-Fi P2P的API有了一定的了解。


一). 配置清单文件

为了使用Wi-Fi P2P,需要在你的清单文件中添加CHANGE_WIFI_STATEACCESS_WIFI_STATEINTERNET权限。虽然Wi-Fi P2P不需要网络连接,但是它使用的是标准的Java套接字,而在Android中使用它们则需要声明对应的权限许可:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.nsdchat"
... <uses-permission
android: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"/>
...

二). 添加一个本地服务

如果你正在提供一个本地服务,你需要为服务搜索注册它。一旦你的本地服务注册了,框架将会自动响应Peer所发起的服务搜索请求。

要创建一个本地服务:

  1. 创建一个WifiP2pServiceInfo对象;
  2. 用你的服务的信息来填充它;
  3. 调用addLocalService()来为服务搜索注册本地服务
     private void startRegistration() {
// Create a string map containing information about your service.
Map record = new HashMap();
record.put("listenport", String.valueOf(SERVER_PORT));
record.put("buddyname", "John Doe" + (int) (Math.random() * 1000));
record.put("available", "visible"); // Service information. Pass it an instance name, service type
// _protocol._transportlayer , and the map containing
// information other devices will want once they connect to this one.
WifiP2pDnsSdServiceInfo serviceInfo =
WifiP2pDnsSdServiceInfo.newInstance("_test", "_presence._tcp", record); // Add the local service, sending the service info, network channel,
// and listener that will be used to indicate success or failure of
// the request.
mManager.addLocalService(channel, serviceInfo, new ActionListener() {
@Override
public void onSuccess() {
// Command successful! Code isn't necessarily needed here,
// Unless you want to update the UI or add logging statements.
} @Override
public void onFailure(int arg0) {
// Command failed. Check for P2P_UNSUPPORTED, ERROR, or BUSY
}
});
}

二). 发现附近的服务

Android会使用回调函数来通知你的应用可以获取的服务,所以要做的第一件事情就是配置它们。创建一个WifiP2pManager.DnsSdTxtRecordListener来监听进入的记录。这个记录作为一个可选项被广播至其它设备。当有一个记录进来了,可以将设备地址以及其它你想要的其它信息拷贝到一个当前方法之外的一个数据结构中,这样你可以在之后的某一个阶段去访问它。下面的例子假设收到的记录包含有一个“buddyname”字段,用以用户身份识别。

final HashMap<String, String> buddies = new HashMap<String, String>();
...
private void discoverService() {
DnsSdTxtRecordListener txtListener = new DnsSdTxtRecordListener() {
@Override
/* Callback includes:
* fullDomain: full domain name: e.g "printer._ipp._tcp.local."
* record: TXT record dta as a map of key/value pairs.
* device: The device running the advertised service.
*/ public void onDnsSdTxtRecordAvailable(
String fullDomain, Map record, WifiP2pDevice device) {
Log.d(TAG, "DnsSdTxtRecord available -" + record.toString());
buddies.put(device.deviceAddress, record.get("buddyname"));
}
};
...
}

要获取服务信息,创建一个WifiP2pManager.DnsSdServiceResponseListener。它接收了实际的描述信息和连接信息。上述代码实现了一个Map对象来将“buddy name”和设备地址配对在一起。服务响应监听器会使用它将DNS记录和对应的服务信息连接到一起。一旦这两个监听器都实现了,使用setDnsSdResponseListeners()方法将它们添加到WifiP2pManager中。

private void discoverService() {
... DnsSdServiceResponseListener servListener = new DnsSdServiceResponseListener() {
@Override
public void onDnsSdServiceAvailable(String instanceName, String registrationType,
WifiP2pDevice resourceType) { // Update the device name with the human-friendly version from
// the DnsTxtRecord, assuming one arrived.
resourceType.deviceName = buddies
.containsKey(resourceType.deviceAddress) ? buddies
.get(resourceType.deviceAddress) : resourceType.deviceName; // Add to the custom adapter defined specifically for showing
// wifi devices.
WiFiDirectServicesList fragment = (WiFiDirectServicesList) getFragmentManager()
.findFragmentById(R.id.frag_peerlist);
WiFiDevicesAdapter adapter = ((WiFiDevicesAdapter) fragment
.getListAdapter()); adapter.add(resourceType);
adapter.notifyDataSetChanged();
Log.d(TAG, "onBonjourServiceAvailable " + instanceName);
}
}; mManager.setDnsSdResponseListeners(channel, servListener, txtListener);
...
}

现在创建一个服务请求并且调用addServiceRequest()。该方法必须接受一个监听器参数来报告结果是成功的还是失败的。

        serviceRequest = WifiP2pDnsSdServiceRequest.newInstance();
mManager.addServiceRequest(channel,
serviceRequest,
new ActionListener() {
@Override
public void onSuccess() {
// Success!
} @Override
public void onFailure(int code) {
// Command failed. Check for P2P_UNSUPPORTED, ERROR, or BUSY
}
});

最后,调用discoverServices()

        mManager.discoverServices(channel, new ActionListener() {

            @Override
public void onSuccess() {
// Success!
} @Override
public void onFailure(int code) {
// Command failed. Check for P2P_UNSUPPORTED, ERROR, or BUSY
if (code == WifiP2pManager.P2P_UNSUPPORTED) {
Log.d(TAG, "P2P isn't supported on this device.");
else if(...)
...
}
});

如果所有代码都运行正常,太好了,你已经做到了!如果你遇到了问题,记住你执行的异步调用会接受一个WifiP2pManager.ActionListener作为参数,然后它会提供给你回调函数来指明成果或失败。若要诊断问题所在,在onFailure()中添加调试代码。该方法提供的错误代码会提示问题产生的原因。下面是一些可能的错误值及它们的含义:

P2P_UNSUPPORTED

在运行程序的设备上不支持Wi-Fi P2P。

BUSY

系统太忙以致无法处理请求。

ERROR

由于一个内部错误导致操作失败。

【Android Developers Training】 77. 使用Wi-Fi P2P进行服务搜索的更多相关文章

  1. 【Android Developers Training】 76. 用Wi-Fi创建P2P连接

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  2. 【Android Developers Training】 74. 序言:通过无线连接设备

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  3. 【Android Developers Training】 75. 使用NSD

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  4. 【Android Developers Training】 9. 覆盖于布局之上的Action Bar

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  5. 【Android Developers Training】 8. 定义Action Bar风格

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  6. 【Android Developers Training】 7. 添加Action Buttons

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  7. 【Android Developers Training】 6. 配置Action Bar

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  8. 【Android Developers Training】 5. 序言:添加Action Bar

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  9. 【Android Developers Training】 4. 启动另一个Activity

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

随机推荐

  1. 添加Metasploit-payload到已有的Android项目中

    metasploit在写这篇文章之前,笔者可以说是对java一窍不通,也从来没有写过什么Android应用,在几天的摸爬滚打中终于实现了最终的目的,就是在已有Apk源码的情况下,用了比较另类的方式,添 ...

  2. Nginx安装lua支持

    Nginx安装lua支持 需要LuaJIT-2.0.4.tar.gz,ngx_devel_kit,lua-nginx-module 1.下载安装LuaJIT-2.0.4.tar.gz wget -c ...

  3. JAVA引用和垃圾回收

    1.强引用(StrongReference) 强引用是使用最普遍的引用.如果一个对象具有强引用,那垃圾回收器绝不会回收它.如下: 1 Object o=new Object();   //  强引用 ...

  4. 【JAVAWEB学习笔记】21_多条件查询、attr和prop的区别和分页的实现

    今天主要学习了数据库的多条件查询.attr和prop的区别和分页的实现 一.实现多条件查询 public List<Product> findProductListByCondition( ...

  5. Java类加载和卸载的跟踪

    博客搬家自https://my.oschina.net/itsyizu/blog/ 什么是类的加载和卸载 Java程序的运行离不开类的加载,为了更好地理解程序的执行,有时候需要知道系统加载了哪些类.一 ...

  6. WINFORM实现进程信息的查看,listview,点击,右键,右键菜单

    1.   程序设计要求 设计程序来获取计算机中的进程信息 2.程序设计流程图 3.程序设计亮点 (0)程序启动时加载guide引导使用视频 (1)使用Listview控件显示出所有控件的名称. (2) ...

  7. Error:Android Source Generator: [sdk] Android SDK is not specified.

    有时候使用intellij idea 带入android 项目,运行提示Error:Android Source Generator: [sdk] Android SDK is not specifi ...

  8. Vulkan Tutorial 02 编写Vulkan应用程序框架原型

    操作系统:Windows8.1 显卡:Nivida GTX965M 开发工具:Visual Studio 2017 General structure 在上一节中,我们创建了一个正确配置.可运行的的V ...

  9. PF2.1版本总结,在设计过程中遇到的问题以及技术分享

    在距离上一次的版本发布已经过去4个月的时间,因为个人的能力以及时间有限,所以这次的版本会推迟这么久.可是无论怎样,PF2.1带着自身的完善总算不负所望推出.在这次的版本调整中让我深有体会到了程序设计中 ...

  10. Windows 7 蓝屏代码大全 & 蓝屏全攻略

    关于Windows 7.Vista等系统的蓝屏,之前软媒在Win7之家和Vista之家都有很多文章讨论过,但是都是筛选的常见的一些问题,今天这个文章是个大全,希望大家看着别头痛,文章收藏下来以后待查即 ...