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