2014-10-05 23 views
0

我已經調查由Android提供的P2P API。我知道所有步驟來發現同伴並連接到他們。我的問題是其他設備如何知道某個設備已將連接創建到我的設備? bcz連接後我們使用套接字來傳輸數據。爲了使套接字工作,客戶端必須知道服務器的IP和端口。這個地址是否需要在客戶端手動輸入? 我的應用程序的流程應該像設備A發現設備,並且一個或多個設備上可能安裝了我的應用程序。 A選擇一個設備併發送連接請求。其他設備可以接受/拒絕該請求。如果接受,那麼這兩個設備應該通過一個作爲服務器的套接字連接,另一個當然是客戶端。 我希望我能很好地解釋我想達到的目標。Android的P2P如何讓客戶知道一個連接建立與設備

回答

0

我目前正在建設一個這樣的應用程序,並不能告訴你的「最佳途徑」來簡化這一過程,但你可能要考慮做P2P服務,因爲這可以防止它被終止/暫停與應用。

如果您選擇不走這條路,但是,你可以使用一個適配器來自動更新包含所有連接的設備到您的設備,以及它們的地址列表視圖。

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(); 
    } 

你應該要連接的設備的地址,您只需撥打連接[索引] .deviceAddress。

相關問題