未调用Android P2P服务发现回调

时间:2015-05-11 01:08:09

标签: android android-networking wifi-direct dns-sd

我对Android很新,我正在开发一个直接通过WIFI交换数据的应用程序,我想使用DNS服务发现而不是纯粹的P2P发现来获取更多有用的信息,比如设备"昵称"等

到目前为止,我已经按照http://developer.android.com/training/connect-devices-wirelessly/index.html上的教程阅读了文档。

我的应用程序似乎成功注册了它的本地服务,并且始终调用来自discoverServices的onSuccess回调,但是从不接收来自其他设备的txtServiceRecord(我使用2个设备)。

这是我的完整代码:

package com.caballero.marco.dnssd_test;

import android.graphics.Color;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.DnsSdTxtRecordListener;
import android.net.wifi.p2p.WifiP2pManager.DnsSdServiceResponseListener;
import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceInfo;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceRequest;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;


import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public class MainActivity extends ActionBarActivity
{
    public static String SERVICE_NAME = "_marcotest";
    private int server_port = 0;
    private WifiP2pManager mManager;
    private Channel channel;
    private ServerSocket serverSocket;
    private TextView txtServiceStatus;
    private Button btnDiscover;
    final HashMap<String, String> buddies = new HashMap<String, String>();
    private ArrayAdapter<String> adapter;
    //private ActionListener serviceDiscoveryListener;
    private WifiP2pDnsSdServiceRequest serviceRequest;
    private DnsSdServiceResponseListener serviceResponseListener;
    private DnsSdTxtRecordListener txtRecordListener;
    private WifiP2pDnsSdServiceInfo serviceInfo;

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

        /* Load controls */
        txtServiceStatus = (TextView)findViewById(R.id.txtStatus);
        btnDiscover = (Button)findViewById(R.id.btnDiscover);
        btnDiscover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startServiceDiscovery();
            }
        });

        mManager = (WifiP2pManager)getSystemService(WIFI_P2P_SERVICE);
        channel = mManager.initialize(this, getMainLooper(), null);
        adapter = new ArrayAdapter<String>( this,
                                            android.R.layout.simple_list_item_1,
                                            new ArrayList<String>());
        /* Initialize Socket Server */
        try {
            initializeSocketServer();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        startRegistration();
        setupDiscoverServices();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    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.
        serviceInfo = WifiP2pDnsSdServiceInfo.newInstance(SERVICE_NAME, "._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 WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                // Command successful! Code isn't necessarily needed here,
                // Unless you want to update the UI or add logging statements.
                SpannableString text = new SpannableString("Online");
                text.setSpan(new ForegroundColorSpan(Color.GREEN), 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                txtServiceStatus.setText(text);
                Log.v("DnsSDTest", "Service added.");
            }

            @Override
            public void onFailure(int arg0)
            {
                // Command failed.  Check for P2P_UNSUPPORTED, ERROR, or BUSY
                SpannableString text = new SpannableString("Offline");
                text.setSpan(new ForegroundColorSpan(Color.RED), 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                txtServiceStatus.setText(text);
            }
        });
    }

    private void initializeSocketServer() throws IOException
    {
        serverSocket = new ServerSocket(0);
        server_port = serverSocket.getLocalPort();
    }

    private void setupDiscoverServices()
    {
        txtRecordListener = new WifiP2pManager.DnsSdTxtRecordListener() {
            @Override
            public void onDnsSdTxtRecordAvailable(String fullDomainName, Map<String, String> txtRecordMap, WifiP2pDevice srcDevice)
            {
                Log.v("DnsSDTest", "DnsSdTxtRecord available -" + txtRecordMap.toString());
                buddies.put(srcDevice.deviceAddress, txtRecordMap.get("buddyname"));
            }
        };

        serviceResponseListener = new DnsSdServiceResponseListener() {
            @Override
            public void onDnsSdServiceAvailable(String instanceName, String registrationType, WifiP2pDevice srcDevice)
            {
                // Update the device name with the human-friendly version from
                // the DnsTxtRecord, assuming one arrived.
                srcDevice.deviceName = buddies
                        .containsKey(srcDevice.deviceAddress) ? buddies
                        .get(srcDevice.deviceAddress) : srcDevice.deviceName;

                // Add to the custom adapter defined specifically for showing
                // wifi devices.
                adapter.add(srcDevice.toString());
                adapter.notifyDataSetChanged();
                Log.v("DnsSDTest", "onBonjourServiceAvailable " + instanceName);
            }
        };

        mManager.setDnsSdResponseListeners(channel, serviceResponseListener, txtRecordListener);
        Log.v("DnsSDTest", "Added DNS SD response listeners.");
    }

    private void startServiceDiscovery()
    {
        serviceRequest = WifiP2pDnsSdServiceRequest.newInstance();
        mManager.addServiceRequest(channel, serviceRequest, new ActionListener() {
            @Override
            public void onSuccess() {
                Log.v("DnsSDTest", "Service Request added successfully!");
            }

            @Override
            public void onFailure(int reason) {
                Log.v("DnsSDTest", "Failed to add service request!");
            }
        });

        mManager.discoverServices(channel, new ActionListener() {
            @Override
            public void onSuccess() {
                Log.v("DnsSDTest", "Service discovery successfull!");
            }

            @Override
            public void onFailure(int reason) {
                Log.v("DnsSDTest", "Service discovery failed :(");
            }
        });
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        mManager.removeLocalService(channel, serviceInfo, new ActionListener() {
            @Override
            public void onSuccess() {
                Log.v("DnsSDTest", "Removed service");
                serviceInfo = null;
            }

            @Override
            public void onFailure(int reason) {
                Log.v("DnsSDTest", "Failed to remove service");
            }
        });
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        if(serviceInfo == null)
        {
            startRegistration();
        }
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();

        try {
            if(!serverSocket.isClosed())
                serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:4)

查找1:

只有在使用setupDiscoverServices()附加两个侦听器(服务侦听器和txtrecord侦听器)之后,才需要为这些附加的列表器创建服务请求并启动发现。您可以随时手动创建服务请求并使用按钮触发发现服务,这很容易出错。在使用按钮调用startServiceDiscovery()之前,无法保证听众实际上已连接。

解决方案1:在设置DNS SD响应侦听器之后,即在mManager.setDnsSdResponseListeners()之后,尝试调用方法startServiceDiscovery(),而不是调用按钮单击Listener。

解决方案2:否则,我建议您移动

'mManager.addServiceRequest(channel, serviceRequest, new ActionListener() {....}'

部分加入'setupDiscoverServices()'方法并尝试激活startServiceDiscovery()的{​​{1}}中的按钮('onSuccess()')。通过这种方式,您可以实现连接侦听器,注册服务和启动发现(手动)之间的同步点

以下链接演示了WiFiDirect项目,其中对等体通过网络服务发现相互连接以进行消息交换。这种方法的顺序要求网络服务发现为我工作。 https://github.com/Hariharan-Gandhi/WiFriends/blob/master/app/src/main/java/tud/cnlab/wifriends/WiFriends.java

发现2: 我还注意到以下行中使用的服务类型是“.tcp”。

'mManager.addServiceRequest'

但是,根据Android开发人员指南,第二个参数(服务类型)应采用以下格式:“_ protocol._transportlayer”。 http://developer.android.com/training/connect-devices-wirelessly/nsd.html。 在这里的演示代码developer.android.com/training/connect-devices-wirelessly/nsd-wifi-direct.html中,他们使用了“_presence._tcp”,其中“presence”是XMPP的消息传递协议。请参阅此处的详细说明Available service types in WifiP2pDnsSdServiceInfo.newInstance

我不确定在SVR记录中省略服务名称是否可以接受 [知识渊博的任何人如果我错了,请更新我的身份]