【问题标题】:Android P2P how does client get to know that a connection is been established with deviceAndroid P2P客户端如何知道与设备建立了连接
【发布时间】:2015-04-04 22:52:38
【问题描述】:

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

【问题讨论】:

    标签: android sockets p2p


    【解决方案1】:

    我目前正在构建这样的应用程序,无法告诉您简化此过程的“最佳方式”,但您可能希望考虑将 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();
        }
    

    如果你想要连接设备的地址,你只需调用connections[index].deviceAddress。

    【讨论】:

      猜你喜欢
      • 2013-04-12
      • 1970-01-01
      • 2012-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-26
      相关资源
      最近更新 更多