Android P2P如何让客户知道已经与设备建立了连接

时间:2014-10-05 14:08:52

标签: android sockets p2p

我已经研究过android提供的P2P API。我知道发现同伴并连接到他们的所有步骤。我的问题是其他设备如何知道某些设备已经为我的设备创建了连接? bcz连接后我们使用套接字传输数据。要使套接字工作,客户端必须知道服务器的IP和端口。这个asdress是否需要在客户端手动输入? 我的应用程序的流程应该像设备A发现设备,并且一个或多个设备可能在其上安装了我的应用程序。 A选择一个设备并发送连接请求。其他设备可以接受/拒绝请求。如果接受,则两个设备应通过套接字连接,一个作为服务器,另一个当然是客户端。 我希望我能很好地解释我想要实现的目标。

1 个答案:

答案 0 :(得分:0)

我目前正在构建这样的应用程序,无法告诉您最好的方式"简化此过程,但您可能希望将P2P视为一项服务,因为这可以防止它被应用程序终止/暂停。

但是,如果您选择不使用该路线,则可以使用适配器自动更新包含设备所有已连接设备及其地址的listView。

public class myActivity extends Activity
{
    WifiP2pManager.Channel myChannel; //This channel is created and passed to system services in order for WIFI_P2P to work
    WifiP2pManager myManager; //This manager is declared to get the required channel object
    List connections;//connections holds all of the connections that the host is dealing with.
    ListView listView;//listView which we will use to display progress bars
    ArrayAdapter<String> adapter;//adapter which is used to update and display the connections

...

protected void onCreate
{
    connections = new ArrayList();//make an arraylist for the connections
    connections.add("No Connected Devices");//say there's no connections as a default
    listView = (ListView)findViewById(R.id.connectionsListView);//initialize the list view
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, connections);//create an array adapter
    listView.setAdapter(adapter);//attach the adapter to the listView

最后,在你的接收器中(特别是在你的WIFI_P2P_CONNECTION_CHANGED_ACTION部分)

public class myBroadcastReceiver
{
    else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action))
    {
        // This is when new connections or disconnections occur
        //WifiP2pInfo info = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_INFO);
        WifiP2pGroup group = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_GROUP);
        myActivity.connections.clear();
        myActivity.connections.addAll(group.getClientList());
        if(myActivity.connections.size() == 0)
        {
            myActivity.connections.add("No Connected Devices");
        }
        myActivity.adapter.notifyDataSetChanged();
    }

您是否需要连接的设备&#39;你只需要调用connections [index] .deviceAddress。